Reputation: 2795
I have a WinForm Application with a grid that contains a ComboBox on each row. All are binded to the same collection ( The collection might change behind that's why I don't want to have different collections for each Combo, also memory cost). The issue is that when I select some object in one combo it changes the selected object on every Combo.. Here is a code you can run and easily reproduce.
public Form1()
{
InitializeComponent();
this.comboBox1 = new System.Windows.Forms.ComboBox();
List<int> numList = new List<int>(){1,2,3,4};
this.comboBox1.FormattingEnabled = true;
this.comboBox1.Location = new System.Drawing.Point(33, 169);
this.comboBox1.Name = "comboBox1";
this.comboBox1.Size = new System.Drawing.Size(126, 21);
this.comboBox1.TabIndex = 3;
this.comboBox1.DataSource = numList; // BINDING TO NUMLIST
this.comboBox2 = new System.Windows.Forms.ComboBox();
this.comboBox2.FormattingEnabled = true;
this.comboBox2.Location = new System.Drawing.Point(243, 367);
this.comboBox2.Name = "comboBox2";
this.comboBox2.Size = new System.Drawing.Size(126, 21);
this.comboBox2.TabIndex = 4;
this.comboBox2.DataSource = numList; // BINDING TO NUMLIST ( THE SAME LIST
this.Controls.Add(this.comboBox2);
this.Controls.Add(this.comboBox1);
}
Just make a form and paste the declaration of the ComboBox 1 and 2. Any Idea how can this be happening. I mean If it is a simple List it doesn't keeps track of selected object. What is happening behind the DataSource?
Upvotes: 1
Views: 176
Reputation: 1062550
The currency-manager is shared whenever you use the same data-source reference. One trick is to set the binding-context per control:
ctrl.BindingContext = new BindingContext();
Another option is to use difference references, for example by abstracting through a different BindingSource
for each control.
Upvotes: 4
Reputation: 8015
Read this: Data Binding in .NET / C# Windows Forms
You will find the behavior you are seeing as actually correct. It is the CurrencyManager that is the root cause.
Upvotes: 1
Reputation: 117220
You need to use seperate lists, if you bind to the same lists, that is the expected behaviour.
Upvotes: 5
Reputation: 23083
When you want to bind, use the linq ToList()
method. This will create a new list though, so they will become unrelated.
Upvotes: 0