删除由特定事件添加的内容 - C#

Remove something added by a particular event - c#

我有一段代码可以在选中复选框时将组合框的选定项目添加到列表框。当复选框未选中时,我想删除要从列表框中删除的选定项目。

我的问题是我不能简单地重复删除代码以使其与添加代码相同,因为组合框选择在未选中时会不同或为空。

这是目前的样子:

private void CBwasher_CheckedChanged(object sender, EventArgs e)
{
     if (checkBox1.Checked == true)
     {
          listBox2.Items.Add(comboBox1.SelectedItem);
     }
     if (checkBox1.Checked == false)
     {
         listBox2.Items.Remove(comboBox1.SelectedItem);
     }

所以我需要一种方法来删除检查更改添加的任何内容,而不是删除组合框的选定索引。请考虑多个不同的复选框添加的列表框中可能有多行。

您只需存储添加的项目并将其删除。

private object addedItem;
private void CBwasher_CheckedChanged(object sender, EventArgs e)
{
     if (checkBox1.Checked)
     {
          addedItem = comboBox1.SelectedItem;
          listBox2.Items.Add(addedItem);
     }
     else
     {
         listBox2.Items.Remove(addedItem);
     }
}

您可能还需要在 adding/removing 项之前检查 SelectedItem 是否为空。

关注您所说的可能有多个不同复选框的部分, 您需要为每个复选框存储一项。

您可以编写自己的 child class 复选框控件来添加此功能,或者简单地使用 Tag 属性。 您还可以以相同的方式指示哪个复选框链接到哪个组合框。 child class 或使用标签 属性.

在我的示例中,我假设您已经使用标签 属性 从复选框中引用了组合框。 你可以像这样手动完成

checkBox1.Tag = comboBox1;

或者希望您可以在动态生成这些内容时将其自动化。

这里是复选框事件的一般概念。 该事件正在使用 sender 参数,这意味着您应该将所有复选框 CheckedChanged 事件连接到这个处理程序。无需为每个创建单独的处理程序。

private void CBwasher_CheckedChanged(object sender, EventArgs e)
{
     var checkBox = (CheckBox)sender;
     var comboBox = (ComboBox)checkBox.Tag;
     if (checkBox.Checked && comboBox.SelectedItem != null)
     {
          listBox2.Items.Add(comboBox.SelectedItem);
          comboBox.Tag = comboBox.SelectedItem;
     }
     if (!checkBox.Checked && comboBox.Tag != null)
     {
         listBox2.Items.Remove(comboBox.Tag);
     }
}