我有一个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/