This a data binding question in C#.
I have a simple Person class:
public class Person {
public string Name {get; set;}
public string Level {get; set;}
}
And I have a Group class, which contains a Persons property as a BindingList of Person instances:
public class Group {
private BindingList<Person> persons_;
public BindingList<Person> Persons {
get { return persons_; }
set { persons_ = value; }
}
}
Finally, I use a BindingSource to connect a group instance to a DataGridView:
// Instantiate a Group instance.
Group p = new Group();
p.Persons = new BindingList<Person> {
new Person {Name = "n1", Level = "l1"},
new Person {Name = "n2", Level = "l2"},
new Person {Name = "n3", Level = "l3"}
};
BindingSource bs = new BindingSource();
bs.DataSource = p;
bs.DataMember = "Persons";
DataGridView dgv = new DataGridView();
dgv.DataSource = bs;
After the above code, the DataGridView will display three Person instances. Everything works fine. Then I have a button, when the button is clicked, I create another Person BindingList and use it to replace p.Persons:
p.Persons = new BindingList<Person> {
new Person {Name = "n10", Level = "l10"},
new Person {Name = "n11", Level = "l11"},
new Person {Name = "n12", Level = "l12"}
};
After the above code, the data binding stops working. Adding ResetBindings() calls from either the BindingSource or the DataGridView doesn't solve the break of the data binding.
Since my BindingSource is bound to the Persons property of the Group class, I think the change of the Persons property should not break the data binding but in fact it does. But this is what we normally do if binding a string property to a Label or TextBox. We just assign a new instance of string to the property and the Label or TextBox will update itself properly. Why this doesn't work for collections of instances? What is the correct code to achieve the same behavior? Thank you very much.