Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

ComboBox with two binding sources

Status
Not open for further replies.

Echilon

Programmer
Feb 22, 2007
54
GB
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. :)
 
I think the problem is you are binding to the Text property of the ComboBox instead of the SelectedValue property:

This:
Code:
this.ddComboBox.DataBindings.Add("Text", bsMainList, "MyObjectID", true, DataSourceUpdateMode.OnPropertyChanged);

should be this:
Code:
this.ddComboBox.DataBindings.Add([b]"SelectedValue"[/b], bsMainList, "MyObjectID", true, DataSourceUpdateMode.OnPropertyChanged);
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top