Scholly
Scholly

Reputation: 43

C# binding to multiple controls - > selection changes at every control

I have a problem with binding to multiple controls. For example I have different controls: 1 listbox, 2 comboboxes, 1 datagridview and all of them have a binding to the same list or iobservablecollection (and except the datagridview display the same property). Everything works fine. But, if I change the selection of one control, the selection of all the other controls change to the same item. Or in other words, if I change the selection of a combobox to item Number 5, the other combobox changes it's selection to Number 5 as well and the listbox changes it's selection also to item Number 5. Does anybody know how to avoid this?

edit: Here's sample code that leads to the same behavior:

private List TestList;

    private void Form1_Load(object sender, EventArgs e)
    {
        TestList = new List<foo>();
        for (int i = 0; i <= 5; i++)
        {
            foo f = new foo();
            f.test = "Test_" + i;
            TestList.Add(f);
        }
        comboBox1.DataSource = TestList;
        comboBox1.DisplayMember = "test";
        comboBox2.DataSource = TestList;
        comboBox2.DisplayMember = "test";
    }

    class foo
    {
        private string _test;
        public string test
        {
            get
            {
                return _test;
            }
            set
            {
                _test = value;
            }
        }
    }

If I change the ite of combobox1 the item of combobox2 changes automatically to the same item.

picture: 1

Upvotes: 1

Views: 625

Answers (2)

Scholly
Scholly

Reputation: 43

I found at least a temporary solution that does not show this behavior.

from:

combobox1.DataSource = TestList;

to:

combobox1.DataSource = Testlist.ToList();

For all who have the same problem, please have a look at these links: https://blogs.msdn.microsoft.com/bethmassi/2007/09/19/binding-multiple-combo-boxes-to-the-same-data-source/

and

One DataSource for multiple controls

Upvotes: 0

Mohamoud Mohamed
Mohamoud Mohamed

Reputation: 525

I would like to see your controls but your datasources for both comboBox1.DataSource = TestList; and comboBox2.DataSource = TestList; are the same. So when you change something in one its going to affect the other.

Upvotes: 0

Related Questions