Him_Jalpert
Him_Jalpert

Reputation: 2516

ArgumentOutOfRangeException when trying to clear combobox

I'm having the following error message appear when trying to run .Clear() on my combobox:

A first chance exception of type 'System.ArgumentOutOfRangeException' occurred in System.Windows.Forms.dll {"InvalidArgument=Value of '-1' is not valid for 'index'. Parameter name: index"}

The strange part is, it does the .Clear() before going to the new 'page' in the application, and it works without a problem. Once I'm on the 'page', draw the items in the combobox and try to go to the next 'page' of the application, it calls the function with the clear once again and blows up when it gets to the .Clear(). If I comment out the cbo.DrawMode = DrawMode.OwnerDrawFixed in the code below it also runs as normal, so the problem is definitely with drawing the strings in the combobox (I'm drawing the strings to change the colour of them). Anyways, completely stumped as to how to fix this, any help would be appreciated.

Code is below:

-My clear method

Public Sub ClearCombos()
    'Clear Applicant Combos

    cboPrimary.Items.Clear() 'crashes when it hits this line
    cboJoin1.Items.Clear()
    cboJoin2.Items.Clear()
    cboJoin3.Items.Clear()
    cboJoin4.Items.Clear()
End Sub

Upvotes: 1

Views: 886

Answers (1)

xpda
xpda

Reputation: 15813

It looks like this shouldn't happen, but it obviously is. The actual error might be in this line in the DrawItem handler:

Dim text As String = (CType(sender, ComboBox)).Items(e.Index).ToString()

Try separating the assignment out of the Dim statement, and check the value of e.Index to make sure it is non-negative. If that's the problem, you could probably work around it with an if to make sure e.Index is non-negative.

Upvotes: 1

Related Questions