/// <summary>
/// 遍历dgv ,赋值给 models
/// </summary>
/// <param name="model">需要赋值的 实体类的模型</param>
/// <param name="dgv"></param>
/// <returns>返回 已赋值的 实体类合集</returns>
public static List<T> FillModelsByDgv<T>( DataGridView dgv, string idColumnName) where T:class ,new()
{
//用于返回的结果
List<T> models = new List<T>();
T model = null;
//遍历 DataGridView 所有行
foreach (DataGridViewRow dgr in dgv.Rows)
{
//判断关键列是否是空,空就跳过
if (dgr.Cells[idColumnName].EditedFormattedValue == null || dgr.Cells[idColumnName].EditedFormattedValue.ToString() == "") continue;
//定义个中间obj
//遍历 DataGridView 所有列
foreach (DataGridViewColumn dgc in dgv.Columns)
{
try
{
//判断当前单元格是否无值,无则跳过
if (dgr.Cells[dgc.Name].EditedFormattedValue == null || dgr.Cells[dgc.Name].EditedFormattedValue.ToString() == "")
continue;
model = new T();
//反射模型的属性
PropertyInfo field = model.GetType().GetProperty(dgc.Name);
//判断当前列类型
switch (dgc.ValueType.ToString())
{
//给模型的属性赋值
case "System.Int32": { field.SetValue(model, int.Parse(dgr.Cells[dgc.Name].EditedFormattedValue.ToString()), null); } break;
case "System.String": { field.SetValue(model, dgr.Cells[dgc.Name].EditedFormattedValue.ToString(), null); } break;
case "System.Decimal": { field.SetValue(model, Decimal.Parse(dgr.Cells[dgc.Name].EditedFormattedValue.ToString()), null); } break;
case "System.DateTime": { field.SetValue(model, DateTime.Parse(dgr.Cells[dgc.Name].EditedFormattedValue.ToString()), null); } break;
case "System.Boolean": { field.SetValue(model, Boolean.Parse(dgr.Cells[dgc.Name].EditedFormattedValue.ToString()), null); } break;
case "System.Char": { field.SetValue(model, dgr.Cells[dgc.Name].EditedFormattedValue.ToString(), null); } break;
default: { } break;
}
}
catch { }
}
//将赋值后的模型添加到 结果集中
models.Add(model);
}
return models;
}
遍历Datagridview所有行 ,赋值给 实体类集
最新推荐文章于 2022-11-03 11:43:21 发布