简体   繁体   English

如何从其valueMember设置comboBox base的选定索引? (C#窗口表单)

[英]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. 我有一个comboBox,显示我国的不同城市(这些城市属于特定省)。 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. 由于存在相同名称的自治市,因此我将“ MunicipalityName”(数据库中“ MUNICIPALITY”表中的表列)绑定到comboBox的DisplayMember属性,并将“ Municipality_ID”绑定到comboBox的ValueMember属性。

When the user saves his details, I supply the SelectedValue from ValueMember of the MUNICIPALITY and insert it to Employee table. 当用户保存他的详细信息时,我从MUNICIPALITY的ValueMember提供SelectedValue并将其插入到Employee表中。

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. 我必须手动检查该员工的Municipality_ID,并将其与comboBox中的绑定数据进行比较,然后遍历它,确定Municipality_ID位于哪个索引,并设置comboBox的SelectedIndex属性。 (Quiet lengthy compared to code snippet below) (与下面的代码段相比,冗长)

I have this code, but I find conflicts since Municipality_Name is not unique. 我有这段代码,但是由于Municipality_Name不是唯一的,所以发现冲突。

//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? 有没有办法像上面的代码一样设置comboBox的SelectedIndex,但是这次将其与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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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