将多个组合框绑定到1个列表<>

时间:2011-01-03 17:01:52

标签: c# .net data-binding

我正在尝试将多个ComboBox绑定到单个List。但是,当我在1个组合框中选择一个值时,绑定到List的所有ComboBox都会更改为相同的值。

List<Country> countryList = new List<Country>();
// Add contries to list.  There are two properties string Name, and string Code
comboBox1.DataSource = countryList;
comboBox1.DisplayMember = "Name";
comboBox1.ValueMember = "Code";


comboBox2.DataSource = countryList;
comboBox2.DisplayMember = "Name";
comboBox2.ValueMember = "Code";

现在,当我从comboBox1中选择一个国家时,它也会选择comboBox2。我不希望为每个ComboBox创建一个单独的列表。

2 个答案:

答案 0 :(得分:4)

抱歉,您必须创建一个新列表。如果你能创建另一个列表。

comboBox2.DataSource = countryList.ToList();

但是,如果这对您不起作用,您可以为其中一个组合框创建一个单独的绑定上下文并按此方式执行

        BindingContext bcG1 = new BindingContext();

        comboBox1.BindingContext = bcG1;

        comboBox1.DataSource = Countries;
        comboBox1.DisplayMember = "Name";
        comboBox1.ValueMember = "Code";

        comboBox2.DataSource = Countries;
        comboBox2.DisplayMember = "Name";
        comboBox2.ValueMember = "Code";

答案 1 :(得分:1)

如果只是一对,可以这样:

comboBox1.DataSource = Countries;
comboBox1.DisplayMember = "Name";
comboBox1.ValueMember = "Code";

comboBox2.DataSource = Countries;
comboBox2.BindingContext = new BindingContext();
comboBox2.DisplayMember = "Name";
comboBox2.ValueMember = "Code";

如果有更多或不同的形式,最好在公共场合创建一种方法:

public ComboBox bindCombo(ComboBox _cb, DataTable _dt)
{
    _cb.DataSource = _dt;
    _cb.BindingContext = new BindingContext();
    _cb.ValueMember = _dt.Columns[0].ToString();
    _cb.DisplayMember = _dt.Columns[0].ToString();
    return _cb;
}