简体   繁体   中英

Retrieve CheckedListBox selected items to Dictionary Winforms c#

I have a dictionary with some data:

        _myDictionary = new Dictionary<string, bool>
        {
            { "a",true},
            { "b",false},
            { "c",true},
            { "d",false},
        };

I want to fill a CheckedListBox with this data, so I do the following:

        foreach (string key in _myDictionary.Keys)
        {
            myCheckedListBox.Items.Add(key, _myDictionary[key]);
        }

until there everything works perfectly. Now I need to update the dictionary with the selected items in the CheckedListBox (update the bool from the pair).

I tried to make a foreach to assign everyone of the pairs in the dictionary, but the CheckedListBox.Items requires an index.

Maybe a dictionary is not the best structure to store this data.

Ant thoughts?

I solved my problem by doing the following:

        for (int i = 0; i < myCheckedListBox.Items.Count; i++)
        {
            string key = (String)myCheckedListBox.Items[i];
            _myDictionary[key] = myCheckedListBox.GetItemChecked(i);
        }

You can do something like this to bind your checkedListBox1 :

(you must track changes manually)

        var list = new List<RandomClass>()
        {
            new RandomClass() {Checked = true, ValueDisplayed = "1"},
            new RandomClass() {Checked = false, ValueDisplayed = "2"},
            new RandomClass() {Checked = true, ValueDisplayed = "3"}

        };
        checkedListBox1.DataSource = list;
        checkedListBox1.DisplayMember = "ValueDisplayed";
        for (int i = 0; i < checkedListBox1.Items.Count; ++i)
        {
            checkedListBox1.SetItemChecked(i, ((RandomClass)checkedListBox1.Items[i]).Checked);
        }
        checkedListBox1.ItemCheck += (sender, e) => {
            list[e.Index].Checked = (e.NewValue != CheckState.Unchecked);
        };   


        public class RandomClass
        {
            public string ValueDisplayed { get; set; }
            public bool Checked { get; set; }
        }

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