如何对ComboBox新增项按字母排序且关联第二个ComboBox匹配项?
问题:ComboBox排序后关联数据不匹配
我已经折腾好几天了,还是没解决这个问题:
- cbFunktion下拉框通过SqlCommand从Funktionstabelle表读取所有行,遍历SqlDataReader把每个
Cat_Funktion值添加到Items集合,同时创建Funktionstabelle对象存入funktionsTabelle列表。 - cbBlock下拉框通过SqlCommand从Hilfstabelle表读取所有行,遍历SqlDataReader创建Hilfstabelle对象存入
hilfsTabelle列表。 - 两个下拉框的
DataSource属性分别绑定对应列表,DisplayMember和ValueMember分别设置为Cat_Funktion和FBlock。 - 往
funktionsTabelle列表新增项后,我会把cbFunktion的DataSource设为null,重新设置DisplayMember、ValueMember和DataSource,最后把选中值更新为新项的FT_ID。
不排序的时候一切正常,但新增的项会排在列表底部,没法按字母排序;排序之后,cbFunktion的项和hilfsTabelle中对应的FBlock值没法正确关联(一个cbFunktion项对应多个cbBlock项)。
以下是我尝试过但没用的代码:
private void UserControl1_Load(object sender, EventArgs e) { // Clear the combo boxes cbFunktion.Items.Clear(); cbBlock.Items.Clear(); // Load Funktion and Hilfstabelle into memory LoadFunktionsTabelle(); LoadHilfsTabelle(); // Sort functionNames using de-DE culture var functionNames = funktionsTabelle.Select(ft => ft.Cat_Funktion).ToList(); //functionNames.Sort(new Comparer()); functionNames = funktionsTabelle.Select(x => x.Cat_Funktion).ToList(); functionNames = functionNames.OrderBy(x => x, new CultureComparer()).ToList(); // Add sorted items to the combo box cbFunktion.Items.AddRange(functionNames.ToArray()); } private void LoadFunktionsTabelle() { con.Open(); SqlCommand cmdFunk = new SqlCommand("Select * from Funktionstabelle", con); SqlDataReader dr = cmdFunk.ExecuteReader(); while (dr.Read()) { funktionsTabelle.Add(new Funktionstabelle() { FT_ID = ((int)dr["FT_ID"]), Cat_Funktion = dr["Cat_Funktion"] as string }); } con.Close(); } private void LoadHilfsTabelle() { con.Open(); SqlCommand cmdBlock = new SqlCommand("Select * from Hilfstabelle", con); SqlDataReader dr1 = cmdBlock.ExecuteReader(); while (dr1.Read()) { hilfsTabelle.Add(new Hilfstabelle() { H_ID = ((int)dr1["H_ID"]), FBlock = dr1["Fblock"] as string, HFT_ID = ((int)dr1["HFT_ID"]) }); } con.Close(); } //Set the data source for cbBlock based on the selected item in cbFunktion private void cbFunktion_SelectedIndexChanged(object sender, EventArgs e) { if (cbFunktion.SelectedIndex != -1) { cbBlock.DataSource = null; // clear the data source int id = funktionsTabelle[cbFunktion.SelectedIndex].FT_ID; cbBlock.DataSource = GetBlockById(id); // set the data source again } else { cbBlock.DataSource = null; } } private string[] GetBlockById(int id) { return hilfsTabelle.Where(line => line.HFT_ID == id).Select(l => l.FBlock).ToArray(); } public class CultureComparer : IComparer<string> { public int Compare(string x, string y) { return CultureInfo.CurrentCulture.CompareInfo.Compare(x, y, CompareOptions.StringSort); } }
这段代码实现了自定义CultureComparer类,继承IComparer<string>接口,可作为OrderBy方法的参数,其Compare方法使用当前文化的字符串排序规则比较字符串。
补充说明:
排序cbFunktion项后,"Funktion"中的选中项与"Block"中的项不匹配,而数据库中是匹配的,该问题仅在排序后出现。
内容的提问来源于stack exchange,提问作者Marco
相关产品推荐
相关产品推荐




