【问题标题】:Retrieve CheckedListBox selected items to Dictionary Winforms c#将 CheckedListBox 选中的项目检索到 Dictionary Winforms c#
【发布时间】:2016-06-20 09:51:58
【问题描述】:

我有一本包含一些数据的字典:

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

我想用这些数据填充 CheckedListBox,所以我执行以下操作:

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

直到一切正常。现在我需要用 CheckedListBox 中的选定项更新字典(更新对中的布尔值)。

我尝试创建一个 foreach 来分配字典中的每个对,但 CheckedListBox.Items 需要一个索引。

也许字典不是存储这些数据的最佳结构。

蚂蚁的想法?

【问题讨论】:

标签: c# winforms dictionary checkedlistbox


【解决方案1】:

我通过执行以下操作解决了我的问题:

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

【讨论】:

    【解决方案2】:

    你可以这样做来绑定你的checkedListBox1

    (您必须手动跟踪更改)

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多