C# Winform 下 DataGridView 行(SelectedRows)转 模型 Model
/// <summary> /// DataRow 转 Model /// </summary> /// <typeparam name="T"></typeparam> /// <param name="row"></param> /// <returns></returns> public static IList<T> DataGridViewSelectedRowsToModel<T>( DataGridView dgv) { IList<T> list = null;
if (dgv != null)
{
list = new List<T>();
foreach (DataGridViewRow dgvr in dgv.SelectedRows)
{
T obj = default(T);
obj = Activator.CreateInstance<T>();
foreach (DataGridViewColumn dgvc in dgv.Columns)
{
PropertyInfo prop = obj.GetType().GetProperty(dgvc.DataPropertyName);
if (prop == null) { continue; }
var dgvrModel = dgvr.Cells[dgvc.Name].Value;
object value = null;
if (dgvrModel != null)
{
value = dgvrModel;
}
//非泛型
if (!prop.PropertyType.IsGenericType)
value = string.IsNullOrEmpty(value + "") ? null : Convert.ChangeType(value, prop.PropertyType);
else//泛型
{
Type genericTypeDefinition = prop.PropertyType.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
value = string.IsNullOrEmpty(value + "") ? null : Convert.ChangeType(value, Nullable.GetUnderlyingType(prop.PropertyType));
}
}
if (prop.CanWrite) //判断其是否可写
prop.SetValue(obj, value, null);
}
list.Add(obj);
}
}
return list; }