[英]Listbox remove wrong item
我的页面上有3个列表框。 我想从列表框中删除一个选定的项目。 在ListBox1中,它的工作原理很好,但是当我从其他ListBoxes中选择项目并单击“删除”时-它总是删除第一个项目。
protected void Button4_Click(object sender, EventArgs e)
{
if (ListBox1.SelectedIndex != -1)
{
ListBox1.Items.Remove(ListBox1.SelectedItem);
}
else if (ListBox2.SelectedIndex != -1)
{
ListBox2.Items.Remove(ListBox2.SelectedItem);
}
else if (ListBox3.SelectedIndex != -1)
{
ListBox3.Items.Remove(ListBox3.SelectedItem);
}
}
这是因为else if
语句无法到达您的其余语句。
尝试这个:
protected void Button4_Click(object sender, EventArgs e)
{
if (ListBox1.SelectedIndex != -1)
ListBox1.Items.Remove(ListBox1.SelectedItem);
if (ListBox2.SelectedIndex != -1)
ListBox2.Items.Remove(ListBox2.SelectedItem);
if (ListBox3.SelectedIndex != -1)
ListBox3.Items.Remove(ListBox3.SelectedItem);
}
如果要删除ListBox项,则应始终检查所有ListBox的选定项,如果未选择第一个ListBox,则在当前代码中检查它,甚至不会检查其余的ListBox项,就像您编写if-else一样阻止。
因此更改如下:
protected void Button4_Click(object sender, EventArgs e)
{
if (ListBox1.SelectedIndex != -1)
{
ListBox1.Items.Remove(ListBox1.SelectedItem);
}
if (ListBox2.SelectedIndex != -1)
{
ListBox2.Items.Remove(ListBox2.SelectedItem);
}
if (ListBox3.SelectedIndex != -1)
{
ListBox3.Items.Remove(ListBox3.SelectedItem);
}
}
绝对不是措辞最好的问题。
也许您只想删除上次使用的ListBox中当前选择的项目?
如果是这样,则创建一个Form级别变量以跟踪哪个ListBox上次更改了它的SelectedIndex:
public partial class Form1 : Form
{
private ListBox CurrentListBox = null;
public Form1()
{
InitializeComponent();
ListBox1.SelectedIndexChanged += new EventHandler(ListBox_SelectedIndexChanged);
ListBox2.SelectedIndexChanged += new EventHandler(ListBox_SelectedIndexChanged);
ListBox3.SelectedIndexChanged += new EventHandler(ListBox_SelectedIndexChanged);
}
void ListBox_SelectedIndexChanged(object sender, EventArgs e)
{
CurrentListBox = (ListBox)sender;
}
private void button4_Click(object sender, EventArgs e)
{
if (CurrentListBox != null && CurrentListBox.SelectedIndex != -1)
{
CurrentListBox.Items.Remove(CurrentListBox.SelectedItem);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.