I use Dapper to bind data to my dataGridView. To fill the dataGridView I receive IEnumerable but this is not sortable. So I use the following method.
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;
}
This works so far.
But I want to use the doubleClick to select a single object from the dataGridView.
Until I used the above method ToDataTable I get the object data this way:
private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex != -1)
{
obj = dataGridView1.Rows[e.RowIndex].DataBoundItem as Part;
...
But now the object always return null.
What do I have to do to get furthermore an object from doubleClick dataGridView?