我在一个名为“GridViewForm”的窗体中有一个数据网格视图。当用户从另一个名为“FindForm”的窗体中搜索搜索框中的文本时,我想突出显示数据网格视图中的所有匹配结果。搜索类型可以是精确的也可以是部分的。
例如。
如果用户搜索文本“stack”,则应突出显示[Stack,stack-over,stacks,stack exchange]中的“stack”字样,并选择与查询匹配的第一个单元格。当用户按下下一步按钮时,应选择与搜索查询匹配的另一个单元格。
我找到文字的代码就像是关注它只搜索确切的单词。
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 windows窗体。提前谢谢。
答案 0 :(得分:3)
您可以使用String.contains而不是=。
以下是关于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
答案 1 :(得分: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,等等。
答案 2 :(得分: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