简体   繁体   中英

Remove selected item from generic list via a button and listbox

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.

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);

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);

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM