I use combobox in c# windows form. I bound the item list as below:
var employmentStatus = new BindingList<KeyValuePair<string, string>>(); employmentStatus.Add(new KeyValuePair<string, string>("0", "[Select Status]")); employmentStatus.Add(new KeyValuePair<string, string>("1", "Contract")); employmentStatus.Add(new KeyValuePair<string, string>("2", "Part Time")); employmentStatus.Add(new KeyValuePair<string, string>("3", "Permanent")); employmentStatus.Add(new KeyValuePair<string, string>("4", "Probation")); employmentStatus.Add(new KeyValuePair<string, string>("5", "Other")); cmbEmployeeStatus.DataSource = employmentStatus; cmbEmployeeStatus.ValueMember = "Key"; cmbEmployeeStatus.DisplayMember = "Value"; cmbEmployeeStatus.SelectedIndex = 0;
I save the selected value in database eg.1 or 2. Now I want to set selected value from database item like:
cmbEmployeeStatus.SelectedValue =employee.employmentstatus;
But combobox not selected with value. How can I do that?
Assign DataTable, setup the ComboBoxes e.g. the DisplayMember and the DataSource (the DataSource will be a BindingSource). Following the above pattern means changing a value in the first ComboBox will automatically change the data source filtered to items relating to the first ComboBox.
When you set the SelectedItem property to an object, the ComboBox attempts to make that object the currently selected one in the list. If the object is found in the list, it is displayed in the edit portion of the ComboBox and the SelectedIndex property is set to the corresponding index.
Try this one.
cmbEmployeeStatus.SelectedIndex = cmbEmployeeStatus.FindString(employee.employmentstatus);
Hope that helps. :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With