DataGridView列填充实体类

使用的地方:
假如你有一个名为rgvProcessDtl的DataGridView控件
DataTable dt = (DataTable)rgvProcessDtl.DataSource;
foreach (DataRow row in dt)
{
OG_ProcessGuidDtl dtl = new OG_ProcessGuidDtl();
FillModel(dtl, row);//将实体类对象与grid行填充

///


/// 将数据填入实体类
///

///
///
public void FillModel(T target, object sourse)
{
if (sourse is DataRow) //源数据为DataRow
{
FillModelByDataRow(target, (DataRow)sourse);
}
if (sourse is T)
{

}

}

///


/// 将DataRow 数据存入T
///

/// 目标
///
private void FillModelByDataRow(T target, DataRow sourse)
{
foreach (PropertyInfo p in typeof(T).GetProperties())
{
try
{
if (sourse[p.Name] != null)
FillModelProperty(target, p.Name, sourse[p.Name]);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}

private void FillModelProperty(T res ,string columnName, object value)
{
PropertyInfo propertyInfo = res.GetType().GetProperty(columnName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
if (propertyInfo != null && value != DBNull.Value)
{
switch (propertyInfo.PropertyType.FullName)
{
case "System.Decimal":
propertyInfo.SetValue(res, Converter.ToDecimal(value), null);
break;
case "System.String":
propertyInfo.SetValue(res, value, null);
break;
case "System.Int32":
propertyInfo.SetValue(res, Converter.ToInt32(value), null);
break;
default:
propertyInfo.SetValue(res, value, null);
break;
}
}
}

posted @ 2024-06-17 09:07  .Net菜鸟站  阅读(1)  评论(0编辑  收藏  举报