Share ComboBox DataSource

跟風遠走 提交于 2019-12-23 07:08:10

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/4861520/share-combobox-datasource

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!