0

I have below piece of code which runs fine only except when the last index of Combobox is reached it gives the error as mentioned in Title. More details: Invalid Argument=Value of '17' is not valid for 'SelectedIndex'. Parameter name: SelectedIndex

The code runs through all the indices available in the Combo-box and gives the desired output. But when the last value is reached I get this error. Could someone please guide me?

Private Sub ExportButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExportButton.Click

        Dim LastItem As Integer = 0
        LastItem = TagComboBox1.Items.Count

        For i As Integer = 0 To LastItem

            TagComboBox1.SelectedIndex = i

         'CODE to perform some operation..

            If TagComboBox1.SelectedIndex = LastItem Then
                 Exit For
            End If

        Next

    End Sub
Matt Wilko
  • 26,994
  • 10
  • 93
  • 143
DK2014
  • 171
  • 3
  • 20

1 Answers1

5

Count returns the number of elements not the highest element index so you need to take 1 off it in your loop:

LastItem = TagComboBox1.Items.Count - 1

See the documentation for this information: ComboBox.ObjectCollection.Count Property

Matt Wilko
  • 26,994
  • 10
  • 93
  • 143
  • 1
    Hi Matt.. truly Appreciate your quick response. It worked great and solved my problem. Thanks again. – DK2014 Aug 13 '14 at 15:10