How to set selected value from Combobox?

thinzar picture thinzar · Jul 14, 2011 · Viewed 239.9k times · Source

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?

Answer

sailhenz picture sailhenz · Jul 14, 2011

Try this one.

cmbEmployeeStatus.SelectedIndex = cmbEmployeeStatus.FindString(employee.employmentstatus);

Hope that helps. :)