繁体   English   中英

C#复选框对话框如何取消选中

[英]C# Checkbox-Dialog How to uncheck

我在C#中有一个Windows窗体对话框,其中显示了字典中每个元素的复选框。 对话框返回一个列表,其中包含所有选定的Elements(复选框)。 但是我注意到,如果我选择一个复选框,然后再次取消选中它,则该元素仍在返回的选定元素列表中。 我怎样才能解决这个问题? 我的对话框如下所示:

public SelectDialog(Dictionary<string, string> Result)
    {
        int left = 45;
        int idx = 0;
        InitializeComponent();
        for (int i = 0; i < Result.Count; i++)
        {
            CheckBox rdb = new CheckBox();
            rdb.Text = Result.Values.ElementAt(i).Equals("") ? Result.Keys.ElementAt(i) : Result.Values.ElementAt(i);
            rdb.Size = new Size(100, 30);
            this.Controls.Add(rdb);
            rdb.Location = new Point(left, 70 + 35 * idx++);
            if (idx == 3)
            {
                idx = 0; //Reihe zurücksetzen
                left += rdb.Width + 5; // nächste Spalte
            }
            rdb.CheckedChanged += (s, ee) =>
            {
                var r = s as CheckBox;
                if (r.Checked)
                    this.selectedString.Add(r.Text);
            };
        }
    }
//Some more Code
}

根据评论:

如果未选中引发事件,则需要从列表中删除项目,我认为您必须检查已添加的项目以避免重复,如果存在则删除项目。 因此处理程序将如下所示:

 rdb.CheckedChanged += (s, ee) =>
        {
            var r = s as CheckBox;
            var itemIndex = this.selectedString.IndexOf(r.Text)
            if (r.Checked && itemIndex == -1) 
                this.selectedString.Add(r.Text);
            else if(!r.Checked && itemIndex != -1)
            {                  
                this.selectedString.RemoveAt(itemIndex);
            }
        };

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM