【问题标题】:I want to show any selected item from CheckedListBox in a ListBox in C#我想在 C# 的 ListBox 中显示 CheckedListBox 中的任何选定项目
【发布时间】:2014-11-04 14:52:02
【问题描述】:

我有一个 Windows 窗体应用程序,其中包含一个名为“ChkBox1”的“CheckedListBox”,它包含这些项目(蓝色、红色、绿色、黄色)。

该表单还包含一个名为“LstBox1”的空“ListBox”。

我希望当我从“ChkBox1”中检查任何项目时,它会添加到“LstBox1”中,当我从“ChkBox1”中取消选中它时,它会从“LstBox1”中删除。

我认为我应该使用“ItemChecked”事件,但我不知道如何检测项目是否已检查并将其添加到另一个列表中。

这是我的尝试:

        private void ChkBox1_ItemCheck(object sender, ItemCheckEventArgs e)
    {
        if (ChkBox1.CheckedItems.Count > 0)
            listBox1.Items.Add(ChkBox1.Items[e.Index]);
        else if (ChkBox1.CheckedItems.Count == 0)
            listBox1.Items.Remove(ChkBox1.Items[e.Index]);
    }

但是当我取消选中它而不是当我选中它时它会添加该项目。

这是另一个尝试:

        private void ChkBox1_ItemCheck(object sender, ItemCheckEventArgs e)
    {

        if (ChkBox1.GetItemChecked(e.Index) == true)
            listBox1.Items.Add(ChkBox1.Items[e.Index]);
        else if (ChkBox1.GetItemChecked(e.Index) == false)
            listBox1.Items.Remove(ChkBox1.Items[e.Index]);
    }

【问题讨论】:

    标签: c# .net winforms listbox


    【解决方案1】:

    试试这个:

    private void ChkBox1_ItemCheck(object sender, ItemCheckEventArgs e)
    {
        if (e.NewValue == CheckState .Checked)
        {
            listBox1.Items.Add(ChkBox1.Items[e.Index]);
        }
        else
        {
            listBox1.Items.Remove(ChkBox1.Items[e.Index]);    
        }
    }
    

    【讨论】:

    • 太好了,谢谢......但为什么你没有让 else 语句最简单
    • @Ahmed.Marzouk 是的,你是对的。没想到
    【解决方案2】:

    “ItemChecked”将向您发送一个“ItemCheckEventArgs”,其中包含旧值和新值。 它还包含已更改值的索引。 您还可以检查“CheckedItems”属性以获取每个已检查的项目:

        private void ChkBox1_ItemCheck(object sender, ItemCheckEventArgs e)
        {
            LstBox1.Items.Clear();
            foreach (var item in ChkBox1.CheckedItems)
                LstBox1.Items.Add(item);
        }
    

    【讨论】:

    • @Ahmed.Marzouk 对不起,我没试过,但它会起作用,你说的“有点错误”是什么意思?
    猜你喜欢
    • 1970-01-01
    • 2012-08-08
    • 1970-01-01
    • 1970-01-01
    • 2018-10-29
    • 1970-01-01
    • 1970-01-01
    • 2014-09-12
    • 1970-01-01
    相关资源
    最近更新 更多