DeveloperLV
DeveloperLV

Reputation: 1781

C# Winforms how to get details of CheckedListBox?

Goal

I am aiming to simply to do the following:

I need to store the information into a Dictionary.

Example

enter image description here

Using hardcoded values just as an example, it'll be something like this:

Dictionary<string, bool> dict = new Dictionary<string, bool>();

dict.Add("No", true);
dict.Add("Product Name", false);
dict.Add("Sign", true);
dict.Add("Month", true);

What I have tried to get details from CheckedListBox:

Dictionary<string, bool> dict = new Dictionary<string, bool>();

foreach(CheckedListBox box in checkedListBox1.Items)
{
    dict.Add(box.Items, box.GetItemChecked);
}

I cannot find any correct properties when using intellisense, I was hoping to get the title of each record and the check state of each record.

Upvotes: 0

Views: 128

Answers (1)

Joshua Robinson
Joshua Robinson

Reputation: 3539

Well, CheckedListBox.Items returns an instance of CheckedListBox.ObjectCollection, so your foreach isn't quite right. I imagine it might look something like this instead...

foreach (object item in checkedListBox1.Items)

But, since you want to know whether each item is checked or not, you'd probably be better off with a for loop to loop through the items instead. You'll need to use CheckedListBox.GetItemChecked(int) to determine if an item is checked or not. That function takes the index of the item you want to check.

Then you can use that index and CheckedListBox.Items to get the text of each individual item. You can call ToString to get the text of the item, assuming that the item isn't null.

Putting it all together might look something like...

for (int i = 0; i < checkedListBox1.Items.Count; i++)
{
    dict.Add(checkedListBox1.Items[i].ToString(), checkedListBox1.GetItemChecked(i));
}

Upvotes: 1

Related Questions