Why does changing a SelectedItem in one Combo change all the other combinations?

I filled comboboxes 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 the problem is that I change SelectedItem in one Combo - does it change in all other Combos?

+6
source share
3 answers

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

t)

 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"; } } 
+12
source

A better approach would be to use a DataView to avoid data duplication. Also, do not drop several times if this 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 that you can do it even cleaner with LINQ

 foreach (ComboBox comboBox in this.Controls.OfType<ComboBox>()) { comboBox.DataSource = new DataView(DataSet1.Tables[0]); comboBox.DisplayMember = "Articles"; } 
+6
source

I had the same problem, but I worked with generics. I used the combo box binding context to get rid of this. (Very useful when you do not know the size of the binding list - in your case, these are 5 elements)

In the code below, DisplayBindItem is just a class with a key and 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"; 

Class for reference.

  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() { } } 

Please mark as an answer if this solves your problem.

+1
source

Source: https://habr.com/ru/post/919321/


All Articles