简体   繁体   中英

C# Winforms how to get details of CheckedListBox?

Goal

I am aiming to simply to do the following:

  • Get details of CheckedListBox .
  • The Title of the CheckedListBox record.
  • The boolean value of the record. In other words, if the record is checked or not checked.

I need to store the information into a Dictionary.

Example

在此处输入图像描述

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.

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

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