Set SelectedItem on a combobox bound to datasource
this works for me
bsCustomers.Position = comboBox.Items.IndexOf(targetCustomer);
Your binding code is not complete. Try this:
BindingSource bsCustomers = new BindingSource();
bsCustomers.DataSource = _customers;
comboBox.DataBindings.Add(
new System.Windows.Forms.Binding("SelectedValue", bsCustomers, "id", true));
comboBox.DataSource = bsCustomers;
comboBox.DisplayMember = "name";
comboBox.ValueMember = "id";
In most cases you can accomplish this task in the designer, instead of doing it in code.
Start by adding a data source in the "Data Sources" window in Visual Studio. Open it from menu View > Other Windows > Data Sources. Add an Object data source of Customer
type. In the Data Sources you will see the customer's properties. Through a right click on the properties you can change the default control associated to it.
Now you can simply drag a property from the Data Sources window to you form. Visual Studio automatically adds A BindingSource
and a BindingNavigator
component to your form when you drop the first control. The BindingNavigator
is optional and you can safely remove it, if you don't need it. Visual Studio also does all the wire-up. You can tweak it through the properties window. Sometimes this is required for combo boxes.
There's only one thing left to do in your code: Assign an actual data source to the binding source:
customerBindingSource.DataSource = _customers;
You should do
comboBox.SelectedValue = "valueToSelect";
or
comboBox.SelectedIndex = n;
or
comboBox.Items[n].Selected = true;