参数超出范围异常未得到处理

DK2*_*014 0 .net vb.net loops outofrangeexception

我有下面的代码只运行正常,除非到达Combobox的最后一个索引,它给出标题中提到的错误.更多细节:无效参数='17'的值对'SelectedIndex'无效.参数名称:SelectedIndex

代码遍历组合框中可用的所有索引并提供所需的输出.但是当达到最后一个值时,我得到了这个错误.有人可以指导我吗?

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
Run Code Online (Sandbox Code Playgroud)

Mat*_*lko 5

Count返回元素的数量不是最高元素索引,因此您需要在循环中取消1:

LastItem = TagComboBox1.Items.Count - 1
Run Code Online (Sandbox Code Playgroud)

有关此信息,请参阅文档:ComboBox.ObjectCollection.Count属性