Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Share ComboBox DataSource

May I ask why does both comboboxes trigger each other such that both have same values? Can't I share a single list and have 2 comboboxes with different selected text?

private void Form1_Load(object sender, EventArgs e)
    {
        BindingList<string> list = new BindingList<string>();
        list.Add("A");
        list.Add("B");
        list.Add("C");
        list.Add("D");

        bind(cbo1, list);
        bind(cbo2, list);
    }

    private void bind(ComboBox combobox, BindingList<string> list)
    {
        // commented lines are in actual code,
        // but appears unimportant in this question
        //combobox.DropDownStyle = ComboBoxStyle.DropDown;
        //combobox.AutoCompleteSource = AutoCompleteSource.ListItems;
        //combobox.AutoCompleteMode = AutoCompleteMode.Suggest;
        combobox.DataSource = list;
        //combobox.Focus();
        //combobox.Text = string.Empty;
        //combobox.SelectedText = string.Empty;
    }

UPDATE: Ok, now I found out the issue is that the DataSource is managed by some BindingContext and CurrencyManager to automatically synchronise the list. But I feel someone must know how to disable this behaviour.

I don't wish to use 2 different lists because I want to be able to modify this single list at runtime and have the changes be reflected on all ComboBoxes. Any method to achieve this would be greatly appreciated.

like image 208
Jake Avatar asked Feb 01 '11 10:02

Jake


1 Answers

You can "solve" it like this:

// combobox.DataSource = list;
var curr = new BindingSource(list, null);        
combobox.DataSource = curr;

There is a default BindingSource (Currencymanager) linked to each Form that was keeping the 2 cbx in sync. But I'm not sure what the exact rules are here. I'm not even sure if the above is a good idea or not.

For small lists I would just make separate copies.

like image 59
Henk Holterman Avatar answered Nov 08 '22 07:11

Henk Holterman