List<Customer> _customers = getCustomers().ToList(); BindingSource bsCustomers = new BindingSource(); bsCustomers.DataSource = _customers; comboBox.DataSource = bsCustomers.DataSource; comboBox.DisplayMember = "name"; comboBox.ValueMember = "id";
Now how do I set the combobox's Item to something other than the first in the list? Tried comboBox.SelectedItem = someCustomer; ...and lots of other stuff but no luck so far...
You should do
comboBox.SelectedValue = "valueToSelect";
comboBox.SelectedIndex = n;
comboBox.Items[n].Selected = true;
comboBox.SelectedValue = customerToSelect.id- AdamMc331 2015-07-21 15:42
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;
BindingSourceas a component to your form in the designer (see
Datasection of the
Toolbox). Then you can set all these properties through the properties window. It is even easier, if you start by defining an object data source in the
Data Sourceswindow in VS. Then you can simply drag the fields from this window to your form and the binding-wire-up is done automatically. A
BindingNavigatorare inserted automatically, if you do so. Then, you can safely remove the
BindingNavigatorif you do not need it - Olivier Jacot-Descombes 2012-04-05 14:29
this works for me
bsCustomers.Position = comboBox.Items.IndexOf(targetCustomer);