简体   繁体   中英

How to get index from selectedvalue of a checkedlistbox control?

Among other controls in a windows form, i have a CheckedListBox containing numerous items.The code for populating the CheckedListBox is:

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";

When i save data in the table, i am saving the 'ValueMember'.Now in Edit mode of the said form, i want CheckedListBox items to be Checked using the valuemember saved earlier.My problem is how to find the index of CheckedListBox items from its valuemember???Hope you understand my question.

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

where

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

This code does not work.Please advice with some code.

Since your data is in a dictionary, the most simple way to find the index by value is finding index of the value in dictionary this way:

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

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