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

yonan2236 picture yonan2236 · Sep 27, 2010 · Viewed 15.6k times · Source

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?

Answer

Jon Skeet picture Jon Skeet · Sep 27, 2010

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?