您可以使用CellFormatting
或RowPrepaint
evant 将某些格式应用于行。在这种情况下,检查触发事件的行的条件并在需要时将格式应用于该行就足够了。(感谢 Plutonix提到 RowPrePaint
这似乎比cellFormatting
这种情况下更快。)
由于仅针对可见行引发事件,因此即使您有太多行也不会有性能问题。无论如何,DataGridView
拥有太多行并不是一个好主意,在这种情况下,您应该使用虚拟化或分页等机制。
例子
不管记录的数量是多少,这里有一个示例,如果您按,我会对FirstName
以您输入的文本开头的行进行着色。如果您输入空字符串并按下所有行将显示为黑色。TextBox1
Button1
TextBox1
Button1
要使示例正常工作,您需要有一个DataGridView1
,TextBox1
和Button1
形式。
Public Class Form1
Dim dt As DataTable
Dim filter As String = ""
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
dt = New DataTable
dt.Columns.Add("FirstName")
dt.Columns.Add("LastName")
dt.Rows.Add("John", "Doe")
dt.Rows.Add("John", "Smith")
dt.Rows.Add("Sara", "Allen")
Me.DataGridView1.DataSource = dt
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
filter = Me.TextBox1.Text
Me.DataGridView1.Invalidate()
End Sub
Private Sub DataGridView1_RowPrePaint(sender As Object, _
e As DataGridViewRowPrePaintEventArgs) Handles DataGridView1.RowPrePaint
If (e.RowIndex < 0 OrElse e.RowIndex = DataGridView1.NewRowIndex) Then Return
Dim row = DataGridView1.Rows(e.RowIndex)
If (String.IsNullOrEmpty(filter)) Then
row.DefaultCellStyle.ForeColor = Color.Black
Else
Dim data = DirectCast(DataGridView1.Rows(e.RowIndex).DataBoundItem, _
DataRowView).Row
If data.Field(Of String)("FirstName").ToLower() _
.StartsWith(filter.ToLower()) Then
row.DefaultCellStyle.ForeColor = Color.Red
Else
row.DefaultCellStyle.ForeColor = Color.Black
End If
End If
End Sub
End Class
笔记
如果您应用到您设置为的RowFilter
数据表,它只显示过滤的行。所以我没有使用它,因为您想将过滤后的行着色为红色,而将其他行着色为黑色,因此我们需要显示所有行。DataSource
DataGridView