1

我正在使用 RowFilter 突出显示 datagridview 中的行,但是当我清除过滤器以查看所有记录时,它会删除我应用的突出显示:

Sorter.DtSample.DefaultView.RowFilter = "FirstName = 'John'" 
For Each R0w In Sorter.DataGridView1.Rows
  R0w.defaultcellstyle.forecolor = Color.Red
  Sorter.DataGridView1(0, R0w.index).Value = True
Next
Sorter.DtSample.DefaultView.RowFilter = ""
4

1 回答 1

1

您可以使用CellFormattingRowPrepaintevant 将某些格式应用于行。在这种情况下,检查触发事件的行的条件并在需要时将格式应用于该行就足够了。(感谢 Plutonix提到 RowPrePaint这似乎比cellFormatting这种情况下更快。)

由于仅针对可见行引发事件,因此即使您有太多行也不会有性能问题。无论如何,DataGridView拥有太多行并不是一个好主意,在这种情况下,您应该使用虚拟化或分页等机制。

例子

不管记录的数量是多少,这里有一个示例,如果您按,我会对FirstName以您输入的文本开头的行进行着色。如果您输入空字符串并按下所有行将显示为黑色。TextBox1Button1TextBox1Button1

要使示例正常工作,您需要有一个DataGridView1,TextBox1Button1形式。

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数据表,它只显示过滤的行。所以我没有使用它,因为您想将过滤后的行着色为红色,而将其他行着色为黑色,因此我们需要显示所有行。DataSourceDataGridView

于 2016-11-02T19:03:04.910 回答