1

首先,我将 DataGridView 的 datacontext 分配给从 Generic Class 获得的Company匿名类型 首选匿名类型以获得要在 DataGridView 中显示的所需列名。

    var companyData = (from c in dataContext.Companies 
           select new 
           {
               Company =c.CompanyName,
               City=c.City.CityName,

           });

    dataGridView.DataContext = companyData;

现在我想在 MouseDoubleClick 事件时获取选择行值。但问题是我无法将匿名类型转换回我的泛型类型 Company。

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);

先感谢您。

4

1 回答 1

1

使用 Extension 方法将 DataGridViewRow 转换为 Any Type

 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>();
        }
于 2012-04-13T06:22:38.140 回答