what is Generic Functions | DataTable to List Model Converter
Generics allow you to define the specification of the data type of programming elements. In other words, generics allow you to write a class or method that can work with any data type.
if you work on MVC and use a sql qurey for database intersection you need to fill value in list of model so this program convert DataTable to ListViewModel for you
GenericFunctions.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Dynamic;
using System.Reflection;
namespace CommonFunctions
{
public static class GenericFunctions
{
/// <summary>
/// pass DataTable in parameter and get data in list type model
/// </summary>
public static List<T> ConvertDataTable<T>(DataTable dt)
{
List<T> data = new List<T>();
foreach (DataRow row in dt.Rows)
{
try
{
T item = ConvertDataRow<T>(row);
data.Add(item);
}
catch (Exception ex) { }
}
return data;
}
/// <summary>
/// pass DataRow in parameter and get data in model
/// </summary>
public static T ConvertDataRow<T>(DataRow dr)
{
Type temp = typeof(T);
T obj = Activator.CreateInstance<T>();
foreach (DataColumn column in dr.Table.Columns)
{
try
{
foreach (PropertyInfo pro in temp.GetProperties())
{
try
{
if (pro.Name == column.ColumnName)
{
var vvv = dr[column.ColumnName];
if (dr[column.ColumnName] is System.DBNull)
{
// pro.SetValue(obj, string.Empty, null);
}
else
{
pro.SetValue(obj, dr[column.ColumnName], null);
}
}
else
{ continue; }
}
catch (Exception ex) { }
}
}
catch (Exception ex) { }
}
return obj;
}
}
}
If you like this blog so pls share and Write Comments about Your experience,
Thank You.

Comments
Post a Comment