Is there “DisplayMember” and “ValueMember” like Properties for CheckedListBox control? C# winforms

人盡茶涼 提交于 2019-12-18 05:44:42

问题


I have this DataTable with the following structure:

ID | VALUE
----------------
1  | Item 1
2  | Item 2
3  | Item 3

And I display the values from the DataTable into a CheckedListBox control by adding each row as an item.

But how can I include the ID? Is there "DisplayMember" and "ValueMember" like Properties for CheckedListBox control?


回答1:


Well yes, there are DisplayMember and ValueMember properties on CheckedListBox, although the docs for ValueMember claim it's "not relevant to this class".

Here's a quick example showing DisplayMember working:

using System;
using System.Drawing;
using System.Windows.Forms;

class Test
{
    static void Main()
    {
        CheckedListBox clb = new CheckedListBox {
            DisplayMember = "Foo",
            ValueMember = "Bar",
            Items = {
                new { Foo = "Hello", Bar = 10 },
                new { Foo = "There", Bar = 20 }
            }
        };
        Form f = new Form
        {
            Controls = { clb }
        };
        Application.Run(f);
    }
}

Also note that the docs state:

You cannot bind data to a CheckedListBox. Use a ComboBox or a ListBox for this instead. For more information, see How to: Bind a Windows Forms ComboBox or ListBox Control to Data.

Given the above code which works, presumably it's talking about more advanced data binding, using DataSource?




回答2:


The DataSource, DisplayMember and ValueMember properties are available for this control but they are not displayed in the IntelliSense: MSDN

You should be able to use them though.




回答3:


Yes there are 'display member' and 'value member' properties in CheckedListBox.

You can set the properties as you do in combobox:

   public void PopulateListBox(System.Windows.Forms.CheckedListBox lb, string displayMember, string valueMember, DataTable data)
   {
        lb.DataSource = data; // where data is the datatable. datatable filled up with //data fetched from database.
        lb.ValueMember = valueMember;
        lb.DisplayMember = displayMember;
   }



回答4:


The french documentation say : Cette propriété ne s'applique pas à cette classe. "This property does not apply for this class". This little line of text is not visible in the us documentation...



来源:https://stackoverflow.com/questions/3801290/is-there-displaymember-and-valuemember-like-properties-for-checkedlistbox-co

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!