Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 863
Sergey Kucher Avatar asked Oct 23 '25 18:10

Sergey Kucher


1 Answers

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();
like image 98
Jason Down Avatar answered Oct 26 '25 09:10

Jason Down



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!