如何从选中列表框控件的选定值获取索引

本文关键字:控件 获取 索引 列表 | 更新日期: 2023-09-27 18:12:01

在windows窗体的其他控件中,我有一个包含许多项的CheckedListBox。填充checklistbox的代码是:

Dictionary<string, string> ciDict = new Dictionary<string, string>();
ciDict.Add("1", "Audi");
ciDict.Add("2", "Suzuki");
ciDict.Add("3", "Saab");
ciDict.Add("4", "Tata");
clb.DataSource = new BindingSource(ciDict, null);
clb.DisplayMember = "Value";
clb.ValueMember = "Key";

当我在表中保存数据时,我正在保存'ValueMember'。现在在上述表单的编辑模式下,我希望使用先前保存的valuemember检查CheckedListBox项。我的问题是如何从它的值成员找到CheckedListBox项目的索引??希望你能理解我的问题。

while (rdrCCA.Read())
{
   int index= clbCSA.Items.IndexOf(rdrCCA["CCA_ITEM_ID"]);
   clbCSA.SetItemChecked(index, true);
}

,

clbCSA= name of the checkedlistbox control
CCA_ITEM_ID = name of the table field where valumember are being stored.

这段代码不起作用。

如何从选中列表框控件的选定值获取索引

由于数据在字典中,因此按值查找索引的最简单方法是在字典中查找值的索引,如下所示:

var index = yourDictionary.Keys.ToList().IndexOf("SomeValue");
if(index > -1)
    checkedListBox1.SetItemChecked(index, true);