0

我正在我的系统中进行搜索,但它说:

Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index

我只能输入一个数字,在我擦除或输入另一个数字后它会弹出错误。

这是我的代码:

  Try
        For row As Integer = 0 To dgv_room.Rows.Count
            If dgv_room.Rows(row).Cells(0).Value.ToString.Substring(0, tbx_search.Text.Length) = tbx_search.Text Then
                dgv_room.Rows(row).Selected = True
                Exit For
            End If
        Next
    Catch ex As Exception
        MessageBox.Show(ex.Message)
    End Try
4

2 回答 2

0

我相信当您在gridview中找不到您的搜索值时会发生错误,因此循环将遍历所有行。

但是,您从 0 循环到 gridview 中的行数,但 gridview 中的行集合是从零开始的,因此您需要将循环中的迭代次数减少一:

  Try
        For Each row As DataGridViewRow In dgv_room.SelectedRows
            row.Selected = False
        Next
        For row As Integer = 0 To dgv_room.Rows.Count - 1
            If dgv_room.Rows(row).Cells(0).Value.ToString.Contains(tbx_search.Text) Then
                dgv_room.Rows(row).Selected = True
                Exit For
            End If
        Next
    Catch ex As Exception
        MessageBox.Show(ex.Message)
    End Try

例如:

假设您的 gridview 中有 5 行,如果您的搜索文本中的任何一个都不存在,那么每次迭代将如下所示:

row = 0 > checks dgv_room.Rows(0)...
row = 1 > checks dgv_room.Rows(1)...
row = 2 > checks dgv_room.Rows(2)...
row = 3 > checks dgv_room.Rows(3)...
row = 4 > checks dgv_room.Rows(4)...
row = 5 > checks dgv_room.Rows(5)... (error here as a Row in the Rows collection with an idex of 5 doesn't exist)
于 2012-08-12T08:49:04.700 回答
0
If dgv_room.Rows(row).Cells(0).Value.ToString.contains(tbx_search.Text) Then

内含更好。我无法理解你的第二个问题,但试试这个。

于 2012-08-12T09:02:47.367 回答