Once again I have a very complicated question so I'll try and explain as well as I can:
I have a C# Windows Forms (.NET 4) program. My Windows Form contains one large blank panel.
Inside this program, I have a Windows Form UserControl class with a designer. The user control is a box with two ComboBoxes and a TextBox on it (call it a menu choice).
Each ComboBox on the user control is bound to a different DataSource using:
comboBoxSelection1.DataSource = SelectionList1;
comboBoxSelection2.DataSource = SelectionList2;
When the user selects an item using the ComboBoxes, the TextBox shows their choices.
E.g. Selection 1: Steak, Selection 2: Chips.
The entire point of this program is to allow the user to create multiple user controls (menu choices) each with different selections, resulting in a list of selections (which becomes one single order).
With me so far?
This worked absolutely fine before I started using DataSource for the ComboBoxes, like so:
object[] comboBoxList1 = new object[SelectionList1.Count];
int i = 0;
foreach (Selection s in SelectionList1)
{
string description = s.Description;
comboBoxList1[i] = description;
i++;
}
comboBoxSelection1.Items.AddRange(comboBoxList1);
However, I need to use a DataSource in order to differentiate items by id (some displayed names are identical - I cannot change this).
I am now using the following:
comboBoxSelection1.DataSource = SelectionList1;
comboBoxSelection1.ValueMember = "Code";
comboBoxSelection1.DisplayMember = "Name";
The problem is that whenever I change comboBoxSelection1 on one of my user controls, the comboBoxSelection1 value on every user control on the panel changes to my current selection. The same happens with comboBoxSelection2 if I change a value in any comboBoxSelection2, all comboBoxSelection2 boxes change to the same value.
Is this a bug with using one DataSource for multiple controls?
It has been seen here: Data Bound ComboBox: List item changed when I select another
In this case, the issue was solved by using DataBindings rather than DataSource.
As seen here: ComboBox SelectedItem vs SelectedValue.
But when I tried this code my ComboBox item list remained empty:
BindingSource comboBoxSelection1Binding = new BindingSource();
comboBoxSelection1.DataSource = SelectionList1;
comboBoxRuleCustomerGroup.DataBindings.Add("SelectedValue", comboBoxSelection1, "Name", true, DataSourceUpdateMode.OnPropertyChanged);
Any ideas?
Sorry for the overly complex issue, I keep having to write overly complex programs!
Did a more detailed search after thinking about this in depth over the weekend. My issue in searching before was not knowing really what was happening. I realise now that this is a problem when trying to bind multiple combo boxes to the same dataset.
Finally found this: Multiple ComboBox controls from the same Dataset
The answer is to add the line:
comboBoxSelection1.BindingContext = new BindingContext();
All credit to Blind Fury/John Saunders and Bytes.com.