[英]Highlight row in a DataGridView without filtering the rest of the data
如何在不過濾視圖中其余數據的情況下突出顯示DataGridView中的行? 我可以基於文本框中的文本在Windows窗體上過濾DataGridView,它僅顯示符合條件的數據。 我不想顯示所有數據,而是只顯示符合搜索條件的行,而不是過濾數據。
任何幫助表示贊賞,我正在使用Visual Basic。
這主要是從C#到VB.Net的轉換,該答案是在以下位置給出的答案: 在DataGridView中的列中搜索值 。 我添加了一些使用“命名”列並清除當前選擇的內容。
我將功能合並到獨立應用程序的上一個答案中。 窗體上有一個DataGridView,Button和一個TextBox,其功能如下。
Public Class Form1
Public Sub New()
' This call is required by the designer.
InitializeComponent()
' Add any initialization after the InitializeComponent() call.
InitialiseData()
DataGridView1.DataSource = People
End Sub
Private People As List(Of Person)
Private Sub InitialiseData()
People = New List(Of Person)()
People.Add(New Person With {.Name = "J1", .Address = "Address1", .Phone = "123"})
People.Add(New Person With {.Name = "J2", .Address = "Address2", .Phone = "456"})
People.Add(New Person With {.Name = "J3", .Address = "Address3", .Phone = "789"})
People.Add(New Person With {.Name = "J4", .Address = "Address4", .Phone = "147"})
People.Add(New Person With {.Name = "J5", .Address = "Address5", .Phone = "258"})
End Sub
Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
Dim searchValue As String = TextBox1.Text
Dim searchColumn As DataGridViewColumn = DataGridView1.Columns("Phone")
DataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect
DataGridView1.ClearSelection()
Try
For Each row As DataGridViewRow In DataGridView1.Rows
If (row.Cells(searchColumn.Index).Value.ToString().Equals(searchValue)) Then
row.Selected = True
Exit For
End If
Next
Catch exc As Exception
MessageBox.Show(exc.Message)
End Try
End Sub
End Class
Public Class Person
Public Property Name As String
Public Property Address As String
Public Property Phone As String
End Class
Dim searchColumn As DataGridViewColumn = DataGridView1.Columns("Phone")
Phone
列設置為搜索條件的目標。
行If (row.Cells(searchColumn.Index).Value.ToString().Equals(searchValue)) Then
進行精確的內容匹配。 在此示例中,如果您在文本框中輸入456
,它將與第二行匹配。
'search amount of rows'
For i = 0 To yourDatagridview.Rows.Count - 1
'if it contains what you have typed in "yourtextbox"
If (yourDatagridview.Rows(i).Cells("date").Value) = yourTextBox.Text Then
'make it red'
yourDatagridview.Rows(i).DefaultCellStyle.BackColor = Color.Red
End If
Next
我希望這是您要尋找的東西?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.