【问题标题】:Can't get Value and DisplayMember from CheckedListBoxControl bound to LINQ无法从绑定到 LINQ 的 CheckedListBoxControl 获取值和 DisplayMember
【发布时间】:2015-04-01 13:49:51
【问题描述】:

这个问题之前在 StackOverflow 上被问过,所以你可能认为它是重复的,但我已经尝试了许多解决方案,但我仍然卡住了。

我有一个绑定到 LINQ 查询的 WinForms CheckedListBoxControl,但我无法获取 Value 和 DisplayMembers。

以下是获取 Value 和 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
        }

【问题讨论】:

  • 什么item.GetType()?您使用标准的CheckedListBox 或一些带有控件的第三方库?
  • 我试过标准的和 DevExpress 的。我不介意哪一个有效。出于本文的目的,我将不得不查看标准控件,因为这不是 devExpress 论坛。
  • item.GetType() = Name = "f__AnonymousTypeb6`2"

标签: c# linq checkedlistbox


【解决方案1】:

假设您只想获取/显示您的 ValueMembers/DisplayMembers: 从您提供的示例中,我假设您从 linq 查询中获得了 IEnumerable<dynamic>。我已经为我的测试场景将它转换为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
}

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 2012-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多