Cyber Space Cyber Space - 1 year ago 137
C# Question

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


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.

Answer Source

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.Cast<string>().ToList().IndexOf("SomeValue");
checkedListBox1.SetItemChecked(index, true);

The keys of your dictionary is string, so I used Cast<string>.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download