2016-11-02 47 views
1

我使用的RowFilter突出在一個DataGridView行,但是當我清除過濾器來查看所有記錄,它刪除我應用的亮點:如何使用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 = "" 
+0

100K實際上是太多的recors。不要在'DataGridView'中顯示所有100K +記錄。使用分頁/過濾機制,只顯示一些行。 –

+0

@RezaAghaei這並不符合我想要完成的。我需要能夠滾動瀏覽所有記錄,以便將所選記錄與非選定記錄進行比較(或非高亮顯示) – Chrisetiquette

+0

因此,請使用['VirtualMode'](https://msdn.microsoft.com/en-us/ 'DataGridView'中的library/15a31akc(v = vs.110).aspx)。 –

回答

1

您可以使用CellFormattingRowPrepaint埃文特申請一些格式化的行。在這種情況下,檢查事件是否被觸發的行的標準就足夠了,如果需要的話,將格式應用到行。 (感謝Plutonix爲mentioningRowPrePaint這似乎是快於cellFormatting在這種情況下)。

由於該事件只是可見的行提出,就不會有即使你有太多的行的性能問題。無論如何,擁有太多行的DataGridView並不是一個好主意,在這種情況下,您應該使用類似於virtualization或分頁的機制。

例無論記錄數的

,這裏是我上色你TextBox1如果按Button1進入,他們的FirstName開始與文本行的例子。如果在TextBox1中輸入空字符串並按Button1,則所有行將顯示爲黑色。

爲了使示例工作,您需要在窗體上有一個DataGridView1TextBox1Button1

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到您設定的DataGridViewDataSource,它只顯示過濾行的數據表。所以我沒有使用它,因爲你想過濾紅色的行和黑色的過濾行,所以我們需要顯示所有的行。

相關問題