Reputation: 236
How can you remove from a generic list via a button with the selected item in a listbox?
This is what I have so far in my button click method:
if (listBox2.SelectedItem != null)
{
listBox1.Items.Add(listBox2.SelectedItem);
listBox2.Items.Remove(listBox2.SelectedItem);
if (listBox2.Items.Count > 0)
{
for (int i = 0; i < listBox2.Items.Count; i++)
{
if (listBox2.GetSelected(i) == true)
{
Foods m = listBox2.SelectedItem as Foods;
list.Remove(m);
}
}
}
}
I assumed the line
list.Remove(m);
would do it but it does not do anything.
Upvotes: 1
Views: 10385
Reputation: 11
Hello dear use the simple code and solve your query.....
private void button4_Click(object sender, EventArgs e)
{
if (this.listBox1.SelectedIndex >= 0)
this.listBox1.Items.RemoveAt(this.listBox1.SelectedIndex);
}
Upvotes: 1
Reputation: 32501
Seems you are removing the SelectedItem before finding it in the for
loop. Not sure but this may helps:
if (listBox2.Items.Count > 0)
{
for (int i = 0; i < listBox2.Items.Count; i++)
{
if (listBox2.GetSelected(i) == true)
{
Foods m = chosenBox.SelectedItem as Foods;
list.Remove(m);
}
}
}
listBox1.Items.Add(listBox2.SelectedItem);
listBox2.Items.Remove(listBox2.SelectedItem);
Upvotes: 1