Strange ListBox.Items IndexOutOfRangeException

OK.. I'm building a plumbing company's job tracker. On each Job there can be multiple plumbers and each of those plumbers might have one more more invoices attached to a job. I've included the image URLs incase they don't show up correctly

First I add a few plumbers and invoices... (http://hillcrestplumbing.com/VBIssues/Step1.JPG)

Then I remove one plumber and his attached invoices... (http://hillcrestplumbing.com/VBIssues/Step2.JPG)

Then when I try to remove a second plumber...(http://hillcrestplumbing.com/VBIssues/exception.JPG)

Should be noted that this is all being declared and fired within the click event of the Remove button on the plumbers' side. What's driving me completely insane is that in the exception shown, i = 1 and j = 0.. There's no fifth row in either list box when the prodecure is called.. PlumberItem = lstPlumbers.SelectedItem.. All the column names are exactly right, case and everything. It never craps out when removing the first plumber, only the second. And it doesn't seem to matter if there's a dozen rows in the Invoice list, or only two, it always picks a number higher than the available rows and craps out.

Please let there be someone who knows what might be going on here (or maybe a better way to do this), lest I might be forced to gouge my eyes out in frustration!

You'll have to excuse the bad image compression, I've only got mspaint to work with on this machine :P


Answer this question

Strange ListBox.Items IndexOutOfRangeException

  • unlikely

    -EDIT-

    Oops!  Sorry! 

    What Richard said!!


    When looping through a collection, if the code in the loop will reduce the size of the collection than you have to run the loop in reverse.

    Instead of doing the While i<lstimvoices.items.count use:

    For i  = lstInvoices.Items.Count - 1 to 0 Step -1

    Always loop backward over a collection if it will shrink while the loop executes.



  • TNROROC

    I'm not sure about your specific error, but when removing items from a collection a for-next loop from max to 0 is usually best. For example:

    For I = lstInvoices.Items.Count -1 To 0 Step -1
    If PlumberItem("ID") = lstInvoices.Items(I).Item("PlumberID") Then
    lstinvoices.Remove(lstInvoices.Items(I))
    End If
    Next


  • Strange ListBox.Items IndexOutOfRangeException