Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove multiple selected items in ListBox?

My windows form contains two listboxes. Listbox1 contains some items in it and listbox2 is empty. When I press a button on the form, then multiple selected items from listbox1 should be removed from Listbox1 and copied to Listbox2.

I tried with foreach loop on listbox1.SelectedItems but it removes only 1 item from list.

Anyone has solution or code for this?

like image 283
sagar Avatar asked Feb 28 '12 13:02

sagar


People also ask

Which method removes all items from a ListBox?

The “Items. Clear” method erases all items in Items property. It clears all items in ListBox control.


2 Answers

You could do all in a single loop. You should use a simple for and loop backwards on SelectedIndices:

private void button1_Click(object sender, EventArgs e) 
{ 
    for(int x = listBox1.SelectedIndices.Count - 1; x>= 0; x--)
    { 
        int idx = listBox1.SelectedIndices[x];
        listBox2.Items.Add(listBox1.Items[idx]); 
        listBox1.Items.RemoveAt(idx);
    } 
} 
like image 153
Steve Avatar answered Sep 17 '22 01:09

Steve


you must store The values, you want to delete in other palce and then delete them from List,Here is sample code:

private void button1_Click(object sender, EventArgs e)
{
    ArrayList tmpArr = new ArrayList();
    foreach (object obj in listBox1.SelectedItems)
    {
        listBox2.Items.Add(obj);
        tmpArr.Add(obj);
    }
    foreach (object obj in tmpArr.ToArray())
    {
        listBox1.Items.Remove(obj);
    }
}
like image 24
MRM Avatar answered Sep 17 '22 01:09

MRM