简体   繁体   English

如何取消选择列表框的项目?

[英]How to deselect item of listbox?

I have a ListBox that when an item is selected, it is shown in a label as well. I have a ListBox that when an item is selected, it is shown in a label as well. However, when I want to remove the selected item, program breaks and shows a NullReferenceException .但是,当我想删除所选项目时,程序会中断并显示NullReferenceException

My code:我的代码:

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    label1.Text = "Your Selected: " + listBox1.SelectedItem.ToString();
}

private void button2_Click(object sender, EventArgs e)
{
    label1.Text = "";
    listBox1.Items.RemoveAt(listBox1.SelectedIndex);
}

It may appear, that there's no selected item in the listbox, so you have to check for that:可能会出现列表框中没有选定项目,因此您必须检查:

   private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
   {
       label1.Text = null == listBox1.SelectedItem 
         ? ""
         : "Your Selected: " + listBox1.SelectedItem.ToString();
   }

   private void button2_Click(object sender, EventArgs e) {
     // Looks redundant, listBox1_SelectedIndexChanged will do 
     //label1.Text = "";    

     // Deselect item, but not remove it
     if (listBox1.SelectedIndex >= 0)
       listBox1.SelectedIndex = -1;

     // In case you want to remove the item (not deselect) - comment out the code below
     // if (listBox1.SelectedIndex >= 0)
     //   listBox1.Items.RemoveAt(listBox1.SelectedIndex);
   }

Edit : as for counting listbox items, there's no event fo this in the current listbox implementation.编辑:至于计算列表框项目,当前列表框实现中没有事件 So you have to do it manually:所以你必须手动完成:

  if (listBox1.SelectedIndex >= 0) {
    listBox1.Items.RemoveAt(listBox1.SelectedIndex);

    lbItemsCount.Text = listBox1.Items.Count.ToString();
  }

Another way is to use click event of the list box , if we do not want to double click the one list box item for the deselection of another list items.另一种方法是使用列表框的单击事件,如果我们不想双击一个列表框项来取消选择另一个列表项。 ex:前任:

private void ListBox_Right_Click(strong textobject sender, EventArgs e)
{
Btn_Left.Enabled = ListBox_Right.SelectedIndex >= 0;
ListBox_Left.ClearSelected(); // to clear the list selection/highlight
Btn_Right.Enabled = false; // for my specification
}
}



private void ListBox_Left_Click(object sender, EventArgs e)
{

Btn_Right.Enabled = ListBox_Left.SelectedIndex >= 0;
ListBox_Right.ClearSelected();  //to clear the list selection/highlight

Btn_Left.Enabled = false;// for my specification
}

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

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