2011-11-02 18 views
1

我在名爲「GridViewForm」的窗體中有一個數據網格視圖。當用戶從另一個名爲「FindForm」的窗體搜索框中搜索文本時,我想突出顯示數據網格視圖中的所有匹配結果。搜索類型可以是確切的或部分的。在vb.net的datagrid視圖中查找文本

例如,

如果用戶搜索文本「堆棧」,則應該突出顯示[堆棧,堆棧,堆棧,堆棧交換]中的單詞「堆棧」,並選擇與查詢匹配的第一個單元格。當用戶按下一個按鈕時,應選擇與搜索查詢匹配的另一個單元格。

我的查找文本的代碼就像是按照它搜索確切的單詞。

 Dim gridRow As Integer = 0 
     Dim gridColumn As Integer = 0 
     For Each Row As DataGridViewRow In AccountsDataGridView.Rows 
      For Each column As DataGridViewColumn In AccountsDataGridView.Columns 
       If TryCastString(AccountsDataGridView.Rows(gridRow).Cells(gridColumn).Value).ToLower = SearchTextBox.Text.ToLower Then 
        'AccountsDataGridView.Rows(intcount).Cells(0).Value = "0" 
        MsgBox("FOUND") 'Should be highlight insted of showing message and the cell should be select. 
       End If 
       gridColumn += 1 
      Next column 
      gridColumn = 0 
      gridRow += 1 
     Next Row 

有什麼辦法可以實現我的概念嗎?我使用的是vb.net窗體。提前致謝。

回答

2

那麼你可以設置單元格背景顏色使用不同的顏色突出顯示所有匹配項,並僅選擇與當前匹配對應的單元格:

Dim searchIndex = 0 
AccountsDataGridView.ClearSelection() 
For Each row As DataGridViewRow In AccountsDataGridView.Rows 
    For each cell As DataGridViewCell in row.Cells 
     If CStr(cell.Value).Contains(SearchTextBox.Text, StringComparison.OrdinalIgnoreCase) Then 
      If searchIndex = m_CurrentSearchIndex Then 
       'This is the cell we want to select 
       cell.Selected = True 
      End If 
      'Yellow background for all matches 
      cell.Style.BackColor = Color.Yellow 
      searchIndex += 1 
     End If 
    Next 
Next 

如果m_CurrentSearchIndex具有的值爲0,它會選擇第一個匹配,爲1的值的第二場比賽,等

3

您可以使用String.contains而不是=。

這裏是關於MSDN文章包含方法:

http://msdn.microsoft.com/en-us/library/dy85x1sa.aspx

代碼是否包含搜索文本樣式的細胞:

Dim someText As String = SearchTextBox.Text 
    Dim gridRow As Integer = 0 
    Dim gridColumn As Integer = 0 
    For Each Row As DataGridViewRow In AccountsDataGridView.Rows 
     For Each column As DataGridViewColumn In AccountsDataGridView.Columns 
      Dim cell As DataGridViewCell = (AccountsDataGridView.Rows(gridRow).Cells(gridColumn)) 
      If cell.Value.ToString.ToLower.Contains(someText.ToLower) Then 
       cell.Style.BackColor = Color.Yellow 
      End If 
      gridColumn += 1 
     Next column 
     gridColumn = 0 
     gridRow += 1 
    Next Row 
+0

謝謝您的答覆。它幫助我在網格中找到物品。我仍然有一個問題,當我使用上面的代碼搜索項目時,它只是突出顯示最後一個匹配項目。我想突出顯示何時找到第一個匹配項目,當用戶點擊下一個時,下一個匹配項目應該突出顯示?你能幫我解決這個問題嗎? – nightfire001

+0

編輯允許風格 – Jay

0
Private Sub TextBox2_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox2.TextChanged 

For Each dr As DataGridViewRow In Me.DataGridView1.Rows 

      If dr.Cells(0).Value.ToString.Contains(TextBox2.Text) Then dr.Visible = True Else dr.Visible = False 


     Next 
    End Sub