gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 21:53:47 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com