2012-02-28 119 views
6

Biểu mẫu cửa sổ của tôi chứa hai hộp danh sách. Listbox1 chứa một số mục trong đó và listbox2 trống. Khi tôi nhấn một nút trên biểu mẫu, thì nhiều mục được chọn từ listbox1 phải được xóa khỏi Listbox1 và được sao chép vào Listbox2.Làm cách nào để xóa nhiều mục đã chọn trong ListBox?

Tôi đã thử với vòng lặp foreach trên listbox1.SelectedItems nhưng nó chỉ xóa 1 mục khỏi danh sách.

Bất kỳ ai có giải pháp hoặc mã cho điều này?

+2

Có thể chúng tôi thấy vòng lặp của bạn không? Bạn có thể có giải pháp, nhưng với một lỗi nhỏ :) – f2lollpll

+1

Có lẽ nó giúp để loại bỏ theo thứ tự ngược lại. – brgerner

Trả lời

19

Bạn có thể làm tất cả trong một vòng lặp. Bạn nên sử dụng một đơn giản cho và vòng lặp ngược trên 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); 
    } 
} 
+0

Cảm ơn bạn mã ur cũng đang hoạt động. 1 cho ans ur. – sagar

2

bạn phải lưu trữ Các giá trị, bạn muốn xóa trong palce khác và sau đó xóa chúng khỏi danh sách, đây là mẫu mã:

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); 
    } 
} 
+0

Cảm ơn bạn. nó hiện đang hoạt động. +1 – sagar

2

Tôi đã làm điều này bằng cách sử dụng các phương pháp CopyTo để sao chép các mục cần một mảng theo chiều dài của tội danh mục đã chọn và sau đó looped xung quanh mảng đó loại bỏ mỗi mục tương ứng từ 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); 
    } 
} 
0

Đối với VS2005 tôi một cái gì đó người sử dụng tương tự như tôi không thể sử dụng .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
for (int x = listBox1.SelectedIndices.Count - 1; x >= 0; x--) 
     { 
      int var = listBox1.SelectedIndices[x]; 
      listBox1.Items.RemoveAt(var); 

     } 

nó Works.

Các vấn đề liên quan