johnildergleidisson
johnildergleidisson

Reputation: 2117

Binding enabled property from CheckedListBox.Items - Winforms

I'm relatively new to winforms programming, coming from ASP.NET and I'm struggling to bind things such as "Enabled" field from checklistbox.items.

For example, I have a:

class A
{
    public string Name {get;set;}
    public bool Enabled {get; set;}
}

I then create a list items A and bind to a checkedlistbox.

List<A> aList = new List<A>(
    new A{Name="Item1", Enabled=true}, 
    new A{Name="Item2", Enabled=false} );

CheckedListBox.DataSource = aList;
CheckedListBox.DisplayMember = "Name";

Finally, how do I make items with "Enabled==false" to show as disabled in the checkedlistbox?

Of course, I'll need to do the same with the Checked property but for sake of simplicity I'm not adding it to the example.

Thanks,

John

Upvotes: 3

Views: 1674

Answers (1)

David Hall
David Hall

Reputation: 33143

You cannot perform this kind of rich databinding with the WinForms CheckedListBox.

You can set the DataSource and then the DisplayMember and ValueMember properties but from there on in you have to do the rest with code (including setting the Enabled and Checked properties)

Set the basic binding as shown below:

checkedListBox.DataSource = aList; 
checkedListBox.DisplayMember = "Name";
checkedListBox.ValueMember = "Name";

From there you will need to iterate over the datasource, setting the individual item properties as needed.

One thing that you might be able to do (I haven't tried this but it should work) is subclass the CheckedListBox and but some custom binding code in the new class.

That might give you a more elegant solution - removing code from the code behind, though depending on your situation might not be worth the effort.

Upvotes: 1

Related Questions