2012-08-12 90 views
0

我正在做的搜索结果在我的系统,但它说:错误的搜索数据网格

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 

回答

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) 
+0

我试了一下,我现在可以输入更多的digts,但选择的行仍然在顶部,当我使用退格时,它再次弹出。 – 2012-08-12 08:57:08

+0

好吧,'.Cells(0)'中的数据是否包含您需要搜索的数据?如果是这样,那么你应该能够删除你的代码中的'.Substring(0,tbx_search.Text)'部分。 – XN16 2012-08-12 09:01:02

+0

对不起,但我仍然没有得到它,如果他们什么都没有找到,我怎么能回到它?我不能使用退后的空间。此代码是搜索 – 2012-08-12 09:05:51

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

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

+0

imageshack.us/photo/my-images/191/errorxp.png我只是提供一个屏幕截图给你,我不能用言语解释抱歉。问题仍然是搜索突出显示不正确 – 2012-08-12 09:31:20