提问人:Jocelyn 提问时间:8/10/2022 更新时间:8/10/2022 访问量:38
C# 可排序 DatagridView 不会强制转换为对象
C# Sortable DatagridView doesn't cast to object
问:
我使用 Dapper 将数据绑定到我的 dataGridView。 为了填充 dataGridView,我收到了 IEnumerable,但这是不可排序的。所以我使用以下方法。
public static DataTable ToDataTable<T>(this IEnumerable<T> collection)
{
DataTable dt = new DataTable("DataTable");
Type t = typeof(T);
PropertyInfo[] pia = t.GetProperties();
//Inspect the properties and create the columns in the DataTable
foreach (PropertyInfo pi in pia)
{
Type ColumnType = pi.PropertyType;
if ((ColumnType.IsGenericType))
{
ColumnType = ColumnType.GetGenericArguments()[0];
}
dt.Columns.Add(pi.Name, ColumnType);
}
//Populate the data table
foreach (T item in collection)
{
DataRow dr = dt.NewRow();
dr.BeginEdit();
foreach (PropertyInfo pi in pia)
{
if (pi.GetValue(item, null) != null)
{
dr[pi.Name] = pi.GetValue(item, null);
}
}
dr.EndEdit();
dt.Rows.Add(dr);
}
return dt;
}
到目前为止,这仍然有效。
但是我想使用 doubleClick 从 dataGridView 中选择单个对象。
在我使用上述方法之前,我以这种方式获取对象数据:ToDataTable
private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex != -1)
{
obj = dataGridView1.Rows[e.RowIndex].DataBoundItem as Part;
...
但是现在对象总是返回 .null
我必须做些什么才能从 doubleClick dataGridView 中获取对象?
答: 暂无答案
评论