Sergey Kucher
Sergey Kucher

Reputation: 4180

Trying to Bind List<T> to CheckedListBox in WinForms c#

I am using WinForms C# Is there any way to get following behavior:

  1. bind List to CheckedListBox
  2. When I add elements to list CheckedList box refereshes
  3. When I change CheckedListBox the list changes

I tried to do the following:

Constructor code:

checkedlistBox1.DataSource = a;
checkedlistBox1.DisplayMember = "Name";
checkedlistBox1.ValueMember = "Name";

Field:

List<Binder> a = new List<Binder> { new Binder { Name = "A" } };

On button1 click:

private void butto1_Click(object sender, EventArgs e)
{
    a.Add(new Binder{Name = "B"});
    checkedListBox1.Invalidate();
    checkedListBox1.Update();
}

But the view does not update .

Thank You.

Upvotes: 4

Views: 9566

Answers (4)

SubqueryCrunch
SubqueryCrunch

Reputation: 1495

The proper way of binding a checked listbox is:

List<YourType> data = new List<YourType>();
checkedListBox1.DataSource = new BindingList<YourType>(data);
checkedListBox1.DisplayMember = nameof(YourType.Name);
checkedListBox1.ValueMember = nameof(YourType.ID);

Note to self.

The issue i have every time binding it is that the properties DataSource, DisplayMember and ValueMember are not suggested by intellisense and i get confused.

Upvotes: 0

Jason Down
Jason Down

Reputation: 22151

Change this line:

List<Binder> a = new List<Binder> { new Binder { Name = "A" } };

to this:

BindingList<Binder> a = new BindingList<Binder> { new Binder { Name = "A" } };

It will just work without any other changes.

The key is that BindingList<T> implements IBindingList, which will notify the control when the list changes. This allows the CheckedListBox control to update its state. This is two-way data binding.

Also, you could change these two lines:

checkedListBox1.Invalidate();
checkedListBox1.Update();

to this (more readable and essentially does the same thing):

checkedListBox1.Refresh();

Upvotes: 7

John Gardner
John Gardner

Reputation: 25106

Does your List<Bender> need to be some kind of observable collection, like ObservableCollection<Bender> instead?

Upvotes: 1

canon
canon

Reputation: 41665

Two things you may wish to look at:

  1. Use a BindingList
  2. Add a BindableAttribute to your Name property

Upvotes: 4

Related Questions