Hello:
I have a question regarding databinding and a ComboBox. I have a class called "Person." Each person has a sibling, and this is wrapped in a property of the class. Now for the UI. I have a form with two controls: a ListBox control and a ComboBox control. The ListBox is just a list of "Person" and ComboBox is a list of "Person" too.
Overall, what I'm trying toaccomplish is thata user canselect a "Person" in the ListBox. Once selected, the user can select another "Person" in the combobox, identifying that Person's sibling. Note: I don't care about error checking such as John being John's own sibling. It's pretty simple.
Here's thecode...
public partial class Form1 : Form
{
private void Form1_Load(object sender, EventArgs e)
{
List<Person> lstPersons = new List<Person>();
Person person1 = new Person("John");
Person person2 = new Person("Betty");
Person person3 = new Person("Gary");
Person person4 = new Person("Susan");
person1.Sibling = person2; // John is Betty's sibling and vice versa
person2.Sibling = person1;
person3.Sibling = person4; // Gary is Susan's sibling and vice versa
person4.Sibling = person3;
lstPersons.AddRange(new Person[] { person1, person2, person3, person4 });
BindingSource bs = new BindingSource();
bs.DataSource = lstPersons;
BindingSource bs2 = new BindingSource();
bs2.DataSource = lstPersons;
this.listBox1.DataSource = bs;
this.comboBox1.DataSource = bs2;
this.comboBox1.DataBindings.Add("SelectedItem", bs, "Sibling", true, DataSourceUpdateMode.OnValidation);
}
public class Person
{
private readonly string _Name;
private Person _Sibling = null;
public Person(string Name)
{
this._Name = Name;
}
public override string ToString()
{
return this._Name;
}
public Person Sibling
{
get
{
return _Sibling;
}
set
{
this._Sibling = value;
}
}
}
Here's my question. If I select a person in the ListBox, the ComboBox will reflect the person's sibling. Now, without changing the sibling in the ComboBox, I select another person from the ListBox. What happens is thatSET on the Person's SIBLINGproperty is called when, in fact, I didn't change the sibling. Why is the SET property being called everytime I select a new user in the ListBox? Is there a way to prevent this from happening and ONLY call set when I actually do change the person's sibling?
Thank you.
Trecius