简体   繁体   中英

How can I set the selected index of a comboBox base from its valueMember? (C# Window Form)

I have a comboBox that displays different Municipalities (these Municipalities belongs to a particular Province) in our country. Since there are Municipalities having the same name, I binded the "MunicipalityName" (a table column from 'MUNICIPALITY' table in my database) to DisplayMember property of the comboBox and "Municipality_ID" to ValueMember property of the comboBox.

When the user saves his details, I supply the SelectedValue from ValueMember of the MUNICIPALITY and insert it to Employee table.

cmd.Parameters.Add(new SqlParameter("@Municipality_ID", (object)comboBoxMunicipality.SelectedValue.ToString()));

I find it hard when it comes to retrieval of data when an Employee needs to update his information. I have to manually check the Municipality_ID of that employee and compare it to the binded data in the comboBox, then loop through it, determine what index that Municipality_ID located, and set the SelectedIndex property of the comboBox. (Quiet lengthy compared to code snippet below)

I have this code, but I find conflicts since Municipality_Name is not unique.

//set SelectedIndex based from DisplayMember of the comboBox    
comboBoxMunicipality.SelectedIndex = comboBoxMunicipality.FindStringExact(dataTable.Rows[0]["MunicipalityName"].ToString());

Is there a way to set the SelectedIndex of the comboBox like the code above, but this time, comparing it to the ValueMember?

Is there a shortcut?

     //something like this?
comboBoxMunicipality.SelectedIndex = 
    comboBoxMunicipality.FindByValue(dataTable.Rows[0]["Municipality_ID"].ToString());

I hope you get my point guys... Please help. Thanks.

这个怎么样?

comboBoxMunicipality.SelectedValue = theMunicipalityIDtoSelect

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM