在datagrid中搜索时出错

时间:2012-08-12 08:36:19

标签: vb.net ms-access

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

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

我只能输入1位数,擦除或输入其他数字后会弹出错误。

这是我的代码:

  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

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分:0)

If dgv_room.Rows(row).Cells(0).Value.ToString.contains(tbx_search.Text) Then

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