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

标签 c# winforms

我有一个ListBox,当选择一个项目时,它也会显示在标签中。但是,当我想删除所选项目时,程序会中断并显示 NullReferenceException

我的代码:

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);
}

最佳答案

列表框中可能出现没有选定的项目,因此您必须检查这一点:

   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);
   }

编辑:对于计数列表框项目,当前列表框实现中没有事件。所以你必须手动完成:

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

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

关于c# - 如何取消选择列表框的项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33652344/

相关文章:

c# - Winforms 在正确的位置将 Tab 插入到 Tab 控件中

.net - 可用文化列表

c#线程访问其他线程

c# - 自定义DatePicker Windows Phone 8.1通用

c# - 删除文件前几个字节的最快方法

c# - 使用 File.Copy 移动文件或将流写入该位置有什么区别吗?

c# - 获取 xml 节点值作为字符串 C#

c# - 如何以编程方式回答 "Yes"到 WebBrowser 控件安全警报