2010-08-02 66 views
5

我有一个组合框,显示我国的不同城市(这些城市属于某个省)。由于有同名的市镇,我将“MunicipalityName”(来自我的数据库中“MUNICIPALITY”表的一个表列)绑定到组合框的DisplayMember属性,将“Municipality_ID”绑定到组合框的ValueMember属性。如何从valueMember中设置组合框基础的选定索引? (C#窗体)

当用户保存他的详细信息时,我从MUNICIPALITY的ValueMember提供SelectedValue并将其插入到Employee表中。

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

当员工需要更新他的信息时,我发现很难谈到检索数据的问题。我必须手动检查该员工的Municipality_ID并将其与组合框中的绑定数据进行比较,然后遍历它,确定Municipality_ID所在的索引,并设置组合框的SelectedIndex属性。 (与下面的代码段相比,安静冗长)

我有这段代码,但是我发现冲突,因为Municipality_Name不是唯一的。

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

有没有像上面的代码一样设置comboBox的SelectedIndex的方法,但是这次将它与ValueMember进行比较?

有没有捷径?

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

我希望你能明白我的观点......请帮忙。谢谢。

回答

6

这个怎么样?

comboBoxMunicipality.SelectedValue = theMunicipalityIDtoSelect 
+1

多么简单,哈哈,谢谢先生......我只是一个编程新手。再次感谢:) – yonan2236 2010-08-02 06:39:24

+1

没问题,Yonan - 享受简单,先生! – 2010-08-02 06:40:48

相关问题