DataGridView.SelectedItem [0]到GenericType

时间:2012-04-13 05:46:06

标签: c# wpf datagridview anonymous-types

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

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

           });

    dataGridView.DataContext = companyData;

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

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

提前谢谢。

1 个答案:

答案 0 :(得分: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>();
        }