Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why changing SelectedItem in one Combo changes all other Combos?

I populated comboboxes in this way

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

But, problem is when I change SelectedItem in one Combo - it becomes changed in all other Combos?

like image 972
Alegro Avatar asked Jun 29 '12 12:06

Alegro


2 Answers

Bind them each to a separate instance of the DataSet1.Table[0].

ie)

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";
    }
}
like image 149
GrandMasterFlush Avatar answered Nov 03 '22 01:11

GrandMasterFlush


A better approach would be to use a DataView to avoid duplicating the data. Also, don't cast multiple times if it can be avoided.

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

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

Edit

I just realized you can do this even cleaner with LINQ

foreach (ComboBox comboBox in this.Controls.OfType<ComboBox>())
{
    comboBox.DataSource = new DataView(DataSet1.Tables[0]);
    comboBox.DisplayMember = "Articles";
}
like image 33
cadrell0 Avatar answered Nov 03 '22 00:11

cadrell0