2015-04-01 28 views
0

StackOverflow之前已經問過這個問題,所以您可能認爲它是重複的,但我嘗試了很多解決方案,但仍然陷入困境。無法從CheckedListBoxControl綁定到LINQ獲取值和DisplayMember

我有一個綁定到LINQ查詢的WinForms CheckedListBoxControl,我無法獲得Value和DisplayMembers。

下面是一些嘗試獲取價值和DisplayMember值:

var avail = from c in dc.CostCenters 
         select new { Item = c.CostCenterID, 
           Description = c.CostCenterID + ": " + c.Description }; 
       myList.DataSource = avail; 
       myList.DisplayMember = "Description"; 


     //Retrieval: 
     foreach (var item in myList.CheckedItems) 
     { 
      DataRowView row = item as DataRowView; //Try 1: row is empty 
      string displayMember = item["Description"]; //Try 2: Cannot apply indexing with [] to an expression of type 'object' 
      var x = item[0]; //Try 3: Cannot apply indexing with [] to an expression of type 'object' 
      row3 = ((DataRowView)myList.CheckedItems[item]).Row; //Try 5 million: Compile error - invalid arguments 
     } 
+0

what' item.GetType()'?你可以使用標準的[CheckedListBox](https://msdn.microsoft.com/ru-ru/library/system.windows.forms.checkedlistbox(v = vs.110).aspx)或者一些帶有控件的第三方庫? – Grundy 2015-04-01 14:07:24

+0

我試過了標準版和DevExpress版。我不介意哪一個可以工作。爲了這篇文章的目的,我不得不看看標準控件,因爲這不是devExpress論壇。 – 2015-04-02 06:01:51

+0

item.GetType()= Name =「<> f__AnonymousTypeb6'2」 – 2015-04-02 06:27:22

回答

0

假設你只是想/顯示您的ValueMembers/DisplayMembers: 從您提供的樣品我假設你得到了IEnumerable<dynamic>您linq查詢。我已經將它轉換爲我的測試場景List<dynamic>

List<dynamic> list = new List<dynamic> 
{ 
    new { Item = 1, Description = "1: Item1"}, 
    new { Item = 2, Description = "2: Item2"} 
}; 

只需添加的BindingSource到CheckedListBox:

BindingSource bindingSource = new BindingSource(list, null); 

checkedListBox1.DataSource = bindingSource; 
checkedListBox1.ValueMember = "Item"; 
checkedListBox1.DisplayMember = "Description"; 

當你選擇了你的項目,你想一下:

var checkedItems = checkedListBox1.CheckedItems; 
foreach (dynamic checkedItem in checkedItems) 
{ 
    Console.WriteLine("valuemember: " + checkedItem.Item); 
    // or whatever code you have 
} 

希望這有助於!