我想在C#的ListBox中显示CheckedListBox中的任何选定项
本文关键字:CheckedListBox 任何选 显示 ListBox | 更新日期: 2023-09-27 18:28:59
我有一个windows窗体应用程序,它包含一个名为"ChkBox1"的"CheckedListBox",它包含这些项(蓝色、红色、绿色、黄色)。
该表单还包含一个名为"LstBox1"的空"ListBox"。
我希望当我从"ChkBox1"中选中任何项目时,它会添加到"LstBox1",当我从"ChkBox1"中取消选中它时,它将从"LstBox2"中删除。
我想我应该使用"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]);
}
试试这个:
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]);
}
}
"ItemChecked"将向您发送一个包含旧值和新值的"ItemCheckEventArgs"。它还包含已更改的值的索引。您还可以检查"CheckedItems"属性以获取每个检查的项目:
private void ChkBox1_ItemCheck(object sender, ItemCheckEventArgs e)
{
LstBox1.Items.Clear();
foreach (var item in ChkBox1.CheckedItems)
LstBox1.Items.Add(item);
}