I'm trying to get databinding to work with a ComboBox. The problem seems to be that I want to fill the combobox from a list, then bind it's selected value to another datasource, so I have two binding sources.
The combox box populates correctly, and if I add a method to the .Validating event, the value is indeed the value I need, yet when the object is saved, it's the displayed value that get's saved.
Here's some code:
// The main List, which has other bindings and works fine
private List<MyObject> mainList = new List<MyObject>();
bsMainList = new BindingSource();
bsMainList.DataSource = mainList;
lstMain.DisplayMember = "Name";
lstMain.ValueMember = "Name";
lstMain.DataSource = bsMainList;
// The combo box
List<KeyValuePair<string, string>> comboBoxList = new List<KeyValuePair<string, string>>();
// method to populate the list omitted
this.ddComboBox.DataSource = comboBoxList;
this.ddComboBox.DisplayMember = "Value";
this.ddComboBox.ValueMember = "Key";
this.ddComboBox.DataBindings.Add("Text", bsMainList, "MyObjectID", true, DataSourceUpdateMode.OnPropertyChanged);
this.ddComboBox.Validating += delegate(object sender, CancelEventArgs e) {
Console.WriteLine(ddComboBox.SelectedItem+" : "+ddComboBox.SelectedValue);
}
The problem is, the value stored in the object (in the "MyObjectID" property) is the name, not the value. The validating method outputs this:
[647756, Default] : 647756
The number is the ID, Default is the name.
Any help is appreciated.
The combox box populates correctly, and if I add a method to the .Validating event, the value is indeed the value I need, yet when the object is saved, it's the displayed value that get's saved.
Here's some code:
// The main List, which has other bindings and works fine
private List<MyObject> mainList = new List<MyObject>();
bsMainList = new BindingSource();
bsMainList.DataSource = mainList;
lstMain.DisplayMember = "Name";
lstMain.ValueMember = "Name";
lstMain.DataSource = bsMainList;
// The combo box
List<KeyValuePair<string, string>> comboBoxList = new List<KeyValuePair<string, string>>();
// method to populate the list omitted
this.ddComboBox.DataSource = comboBoxList;
this.ddComboBox.DisplayMember = "Value";
this.ddComboBox.ValueMember = "Key";
this.ddComboBox.DataBindings.Add("Text", bsMainList, "MyObjectID", true, DataSourceUpdateMode.OnPropertyChanged);
this.ddComboBox.Validating += delegate(object sender, CancelEventArgs e) {
Console.WriteLine(ddComboBox.SelectedItem+" : "+ddComboBox.SelectedValue);
}
The problem is, the value stored in the object (in the "MyObjectID" property) is the name, not the value. The validating method outputs this:
[647756, Default] : 647756
The number is the ID, Default is the name.
Any help is appreciated.