0

I have a webform that has two multiselect ListBoxes and a button. The button moves the selected items from one ListBox to the other, while checking for duplicates. Unfortunately I am getting an out of range exception on the last iteration of the loop on the lstEmployees.Items(i).Selected.

I realized what is happening is when I remove an item (lstEmployees.Items.Remove(li)) it changes the count and then throws the error eventually. Is there a way I can remedy this situation?

If Not lstEmployees.SelectedItem Is Nothing Then
    For i As Integer = 0 To lstEmployees.Items.Count - 1
        If lstEmployees.Items(i).Selected = True Then
             li.Text = lstEmployees.Items(i).Text
             li.Value = lstEmployees.Items(i).Value
             If Not lstSelected.Items.Contains(li) Then
                  lstEmployees.Items.Remove(li)
                  lstSelected.Items.Add(li)
             End If
         End If
     Next
End If
todd.pund
  • 689
  • 2
  • 11
  • 36

1 Answers1

1

When you loop over a collection of items and remove items from that collection, the count of items in the collection changes and your check to exit the for loop fails (not considering also that when you remove an item (say at index 5) the item that was at index 6 slips into 5th position and you skip over that element)

The fix is simple. Loop in reverse order

If Not lstEmployees.SelectedItem Is Nothing Then
    For i As Integer = lstEmployees.Items.Count - 1 To 0 Step -1
       ....
    Next
End If
Steve
  • 213,761
  • 22
  • 232
  • 286