How to delete multiple selected items in a ListBox?

My window form contains two lists. Listbox1 contains some items in it, and listbox2 is empty. When I click on the button on the form, then several selected items from list1 should be removed from list1 and copied to Listbox2.

I tried using the foreach loop in listbox1.SelectedItems, but it only removes 1 item from the list.

Does anyone have a solution or code for this?

+6
source share
5 answers

You can do everything in one cycle. You should use a simple for and loop back to 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); } } 
+19
source

you must save the values ​​that you want to remove in the other palm and then remove them from the list. Here is a 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); } } 
+2
source

I did this using the CopyTo method to copy elements into an array along the length of the count of selected elements, and then looped around this array, removing each corresponding element from ListBox1.

  private void button1_Click(object sender, EventArgs e) { object[] itemsToRemove = new object[listBox1.SelectedItems.Count]; listBox1.SelectedItems.CopyTo(itemsToRemove, 0); foreach (object item in itemsToRemove) { listBox1.Items.Remove(item); listBox2.Items.Add(item); } } 
+2
source

For VS2005, I am a user of something similar, as I could not use .selectedIndices

  for (int i = ListBox1.Items.Count - 1; i >= 0; i--) { if (ListBox1.Items[i].Selected) { ListBox2.Items.Add(ListBox1.Items[i]); ListBox1.Items.Remove(ListBox1.Items[i]); } } 
0
source
  for (int x = listBox1.SelectedIndices.Count - 1; x >= 0; x--) { int var = listBox1.SelectedIndices[x]; listBox1.Items.RemoveAt(var); } 

His works.

0
source

Source: https://habr.com/ru/post/909554/


All Articles