Search code examples
winformsdata-bindingdatasourcebindingsource

Updating of BindingSource in WinForms


During my attempts to use DataBinding in Winforms I've encountered with a problem. It looks like after updating of DataSource DataGridView doesn't refresh the data. Can't understand where is a problem.

var companies = new List<Company> { new Company { Name = "Test", Id = 100 }}

And here is the code for binding of items list to DataGridView:

bindingSource1.DataSource = _context.Companies;
dataGridView1.DataSource = bindingSource1.DataSource;

But after that if I update companies list like this

 companies.Add(new Company { Name = "MDG", Id = 500 });

I can't find the newly added item into the DataGridView. Could someone help me to understand what I'm missing?


Solution

  • The problem here is that there is no way the BindingSource and the DataGridView can be made aware of changes to a List automatically.

    Instead, use a new BindingList(). This has events that will be called to notify the BindingSource, and in turn the DataGridView that a new item to the list has been added.

    var companies = new BindingList<Company>();
    companies.Add(new Company { Name = "Test", Id = 100 });