Reputation: 2633
I thought this was a simple problem, but I can't find any information on the web. I'm binding a ListBox to a List
using BindingSource
like so:
List<Customer> customers = MyMethodReturningList();
BindingSource customersBindingSource = new BindingSource();
customersBindingSource.DataSource = customers;
customersListBox.DataSource = customersBindingSource;
Now, when I add or delete from customers
list, my ListBox
gets updated (even without using ResetBindings
on BindingSource
), but if I change any of the customer objects in the list, it does not. Calling ResetBindings
has no effect. I even implemented my own BindingList
, but the behaviour hasn't changed.
The Customer
class uses properties for accessing and modification of data. Its ToString()
content is displayed in the list.
I'm using C# in .Net 2.0.
Any ideas?
Thanks
Upvotes: 7
Views: 13675
Reputation: 1185
I understand that this question was asked almost 6 years ago but other than work-arounds I do not see a correct answer here.
When you change property of an item in a collection the event gets raised for the element (object) but not the collection. So the collection does not see a change and will not refresh bound controls. Elements inside all binding collections and most generic collections like List<>
receive 2 events, PropertyChanging
and PropertyChanged
. When a property of the element inside collection is changed, the event gets triggered. All you need to do is add an event handler that would trigger either re-binding or raise an event on the Collection
.
Upvotes: 0
Reputation: 1157
I got around this problem by converting data to array when updating source. Please see UpdateData method. This way you can update your combo box without losing ComboBox Settings.
class Person {
public int Id {get; set; }
public string FirstName{ get; set; }
public string SurName {get; set; }
}
public Form1()
{
InitializeComponent();
comboBox1.DisplayMember = "FirstName";
comboBox1.ValueMember = "Id";
comboBox1.DataSource = m_PersonList;
}
public void UpdateData() {
m_PersonList[0].FirstName = "Firstname1";
comboBox1.DataSource = m_PersonList.ToArray<Person>();
}
Upvotes: 0
Reputation: 2620
If you use a BindingList
you don't even need the BindingSource
:
BindingList<Customer> customers = new BindingList<Customer>(MyMethodReturningList());
customersListBox.DataSource = customers;
Upvotes: 5
Reputation:
There is also a bug in the list box which can cause this problem. If you set the SelectionMode to None this problem appears.
As a work around I set the selection mode to One and then back to None when updating the datasource.
Upvotes: 3
Reputation: 49
OK, here's a dirty fix: wenever you need to refresh the box contents set datasource = null, then rebind it.
the reason it doesn't update is because the objects in the list haven't changed and it only checks the refrences of the object rather than their contents.
Upvotes: 4