2012-04-13 23 views
1

首先,我將DataGridView的datacontext分配給從通用類Company獲取的匿名類型。首選匿名類型以獲取要在DataGridView中顯示的所需列名稱。DataGridView.SelectedItem [0]到GenericType

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

預先感謝您。

+0

但我不明白的顯示用途所需的列名。我已經提到了我使用匿名類型的目的 – Marshal 2012-04-13 05:59:28

+0

我不認爲有任何更乾淨的方法來做到這一點,雖然有一些黑客。您應該製作一個具體的類(用於命名),並通過LINQ查詢而不是匿名類型製作類對象列表 – 2012-04-13 06:23:57

+0

爲什麼您需要將對象轉換回公司?最初的「公司」從哪裏來? – phoog 2012-04-13 06:27:03

回答

1

使用分機方法的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>(); 
     } 
相關問題