DataGridView.SelectedItem[0] to GenericType

本文关键字:to GenericType SelectedItem DataGridView | 更新日期: 2023-09-27 18:31:03

首先,我将 DataGridView 的数据上下文分配给从泛型类获得的匿名类型Company首选匿名类型以获取要在 DataGridView 中显示的所需列名。

    var companyData = (from c in dataContext.Companies 
           select new 
           {
               Company =c.CompanyName,
               City=c.City.CityName,
           });
    dataGridView.DataContext = companyData;

现在我想在鼠标双击事件时获取选择行值。但问题是我无法将匿名类型转换回我的泛型类型公司。

void dataGridView_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
           var selectedRow = dataGridView.SelectedItem[0];
           // How to convert selectedRow back to Company ? 
           // Anonymous type have no implementation of AsEnumerable.
}

我想要这样的东西:

Company company = selectedRow.Select(c=>new Company
                                    (CompanyName=selectedRow.Company,
                                     CityName=selectedRow.City);

提前谢谢你。

DataGridView.SelectedItem[0] to GenericType

使用 Extension 方法将 DataGridViewRow 转换为任何类型

 public static class DataGridViewRowWExtenstions
    {
        public static T GetObject<T>(this DataGridViewRow Row) where T : new()
        {
            List<PropertyInfo> properties = typeof(T).GetProperties().ToList();
            return CreateItemFromRow<T>(Row, properties);
        }
        private static T CreateItemFromRow<T>(DataGridViewRow row, List<PropertyInfo> properties) where T : new()
        {
            T item = new T();
            foreach (var property in properties)
            {
                if (row.DataGridView.Columns.Contains(property.Name))
                {
                    if (row.Cells[property.Name] != null)
                        property.SetValue(item, row.Cells[property.Name].Value, null);
                }
            }
            return item;
        }
    }

private void dataGridView2_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            DataGridViewRow selectedRow = dataGridView2.SelectedRows[0];
            Company company = selectedRow.GetObject<Company>();
        }