为什么在一个Combo中更改SelectedItem会更改所有其他Combos?

Ale*_*gro 8 c# combobox winforms

我用这种方式填充了组合框

foreach (Control c in this.Controls)
{
     if (c is ComboBox)
     {
         (c as ComboBox).DataSource = DataSet1.Tables[0];
         (c as ComboBox).DisplayMember = "Articles";
     }
}
Run Code Online (Sandbox Code Playgroud)

但是,问题是当我在一个组合中更改SelectedItem时 - 它在所有其他组合中变得更改了吗?

Gra*_*ush 14

将它们绑定到DataSet1.Table [0]的单独实例.

即)

foreach (Control c in this.Controls)
{
    if (c is ComboBox)
    {
        DataTable dtTemp = DataSet1.Tables[0].Copy();
        (c as ComboBox).DataSource = dtTemp 
        (c as ComboBox).DisplayMember = "Articles";
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 根据 ComboBox 的数量和 DataTable 中的数据量,这可能会由于数据重复而导致应用程序的内存占用量大幅增加。 (2认同)

cad*_*ll0 6

更好的方法是使用DataView来避免重复数据.此外,如果可以避免,不要多次投射.

foreach (Control c in this.Controls)
{
    ComboBox comboBox = c as ComboBox;

    if (comboBox != null)
    {        
        comboBox.DataSource = new DataView(DataSet1.Tables[0]);
        comboBox.DisplayMember = "Articles";
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑

我刚刚意识到你可以用LINQ做到更清洁

foreach (ComboBox comboBox in this.Controls.OfType<ComboBox>())
{
    comboBox.DataSource = new DataView(DataSet1.Tables[0]);
    comboBox.DisplayMember = "Articles";
}
Run Code Online (Sandbox Code Playgroud)


Has*_*ash 6

我遇到了同样的问题,但我正在使用泛型。我已经使用组合框的绑定上下文来摆脱这个问题。(当您不知道绑定列表的大小时非常有用 - 在您的情况下它是 5 个项目)

在下面的代码中 DisplayBindItem 只是一个具有 Key 和 Value 的类。

    List<DisplayBindItem> cust = (from x in _db.m01_customers
            where x.m01_customer_type == CustomerType.Member.GetHashCode()
            select new DisplayBindItem
            {
                Key = x.m01_id.ToString(),
                Value = x.m01_customer_name
            }).ToList();

    cmbApprover1.BindingContext = new BindingContext();
    cmbApprover1.DataSource = cust;
    cmbApprover1.DisplayMember = "Value";
    cmbApprover1.ValueMember = "Key";

    //This does the trick :)
    cmbApprover2.BindingContext = new BindingContext();
    cmbApprover2.DataSource = cust ;
    cmbApprover2.DisplayMember = "Value";
    cmbApprover2.ValueMember = "Key";
Run Code Online (Sandbox Code Playgroud)

类供您参考。

    public class DisplayBindItem
    {
        private string key = string.Empty;

    public string Key
    {
        get { return key; }
        set { key = value; }
    }
    private string value = string.Empty;

    public string Value
    {
        get { return this.value; }
        set { this.value = value; }
    }

    public DisplayBindItem(string k, string val)
    {
        this.key = k;
        this.value = val;
    }

    public DisplayBindItem()
    { }
}
Run Code Online (Sandbox Code Playgroud)

如果这解决了您的问题,请标记为答案。