[英]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.