开发者

Share ComboBox DataSource

开发者 https://www.devze.com 2023-02-08 08:44 出处:网络
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?

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开发者_JAVA百科 be greatly appreciated.


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.


You cannot use the same object as the datasource for 2 seperate combo boxes. You should have list1 and list2 defined and populate each combobox with each one. Using the same datasource means that a selection in one combobox is reflected in the other.

0

精彩评论

暂无评论...
验证码 换一张
取 消