using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Reflection;
namespace ClassLibrary1
{
public static class DataTableHelper
{
public static T FillEntityWithDataRow<T>(DataRow drInfo) where T : class,new()
{
T entity = new T();
Type type = entity.GetType();
PropertyInfo[] props = type.GetProperties();
foreach (PropertyInfo prop in props)
{
if (drInfo.Table.Columns[prop.Name] != null)
{
string drValue = drInfo[prop.Name] == DBNull.Value ? "" : drInfo[prop.Name].ToString();
switch (prop.PropertyType.Name)
{
#region 基本属性
case "DateTime":
DateTime dtValue;
if (DateTime.TryParse(drValue, out dtValue))
{
prop.SetValue(entity, dtValue, null);
}
break;
case "Boolean":
bool bValue = false;
if (bool.TryParse(drValue, out bValue))
{
prop.SetValue(entity, bValue, null);
}
break;
case "Int32":
int iValue = 0;
if (int.TryParse(drValue, out iValue))
{
prop.SetValue(entity, iValue, null);
}
break;
case "Int64":
long lValue = 0;
if (long.TryParse(drValue, out lValue))
{
prop.SetValue(entity, lValue, null);
}
break;
case "Double":
double dValue = 0;
if (double.TryParse(drValue, out dValue))
{
prop.SetValue(entity, dValue, null);
}
break;
case "Single":
float fValue = 0;
if (Single.TryParse(drValue, out fValue))
{
prop.SetValue(entity, fValue, null);
}
break;
case "String":
prop.SetValue(entity, drValue, null);
break;
#endregion
}
}
}
return entity;
}
public static List<T> FillListWithDataTable<T>(DataTable dtInfo) where T: class,new()
{
List<T> list = new List<T>();
foreach (DataRow drinfo in dtInfo.Rows)
{
list.Add(FillEntityWithDataRow<T>(drinfo));
}
return list;
}
}
}
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Data;using System.Reflection;namespace ClassLibrary1{ public static class DataTableHelper