2012-09-22 23 views
1

我有以下代碼來填充的DataGridViewLINQ到的DataGridView和回KeyValuePair(或類似)

 var results = from loc in dtLocations.AsEnumerable() 
         join con in dtContacts.AsEnumerable() on (int)loc["contactid"] equals (int)con["id"] 
         select new 
         { 
          id = con["id"], 
          mpoc = loc["mpoc"], 
          directno = loc["directno"], 
          extension = loc["extension"], 
          faxno = loc["faxno"], 
          billing = con["billing"], 
          fullname = con["fullname"], 
          mobno = con["mobno"], 
          email = con["email"] 
         }; 

     dgv.AutoGenerateColumns = false; 
     dgv.DataSource = results.ToList<object>(); 

,但我不能在當我點擊細胞

private void dgvLocations_CellContentClick(object sender, DataGridViewCellEventArgs e) 
    { 
     DataGridView dgv = sender as DataGridView; 
     ????? vals = ((List<object>)dgv.DataSource)[e.RowIndex]; 
     object id = vals.id; //errors of course 
    } 

我讀回可以在Visual Studio的Watcher面板中看到它可以確定列表中的元素,但我無法弄清楚需要設置val以便再次讀取它們的類型:(

enter image description here

+0

它是一個匿名類型。 *不能*以靜態類型表示(除了引入時)。使用命名(非匿名)類型或「動態」或(甚至是ickier,「對象」和顯式反射)。 – 2012-09-22 22:22:08

回答

1

它(new { .. })引入anonymous type。匿名類型不能由由靜態已知(「編譯時」)名稱指定。

使用命名(非匿名)型(其中MyRow是具有所要求的性質已經定義的類):

// Put data in non-anonymous type 
select new MyRow { 
    id = .., 
} 

// Now can use a name statically 
MyRow row = (MyRow)data[rowIndex]; 

另外,dynamic類型可以與C#/ NET4 +使用。或者,甚至更狡猾,object和明確反映。 (請注意,dynamic-type表達式會自動處理惡意反射;與object一樣,靜態類型信息仍然丟失。)

+0

嗨Pst。你能否詳細說明'動態'還是讓我進一步閱讀?非常感激! – Christian

+0

@Christian添加了一個引用(並修正了無意義覆蓋: - /) – 2012-09-22 22:28:14