I am using RowFilter to highlight rows in a datagridview, but when i clear the filter to view all records it removes the highlight i applied:
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 = ""
You can use
CellFormattingorRowPrepaintevant to apply some formatting to rows. In this case it's enough to check the criteria for the row which the event if fired for it and apply the format to the row if required. (Thanks to Plutonix for mentioningRowPrePaintwhich seems to be faster thancellFormattingin this case.)Since the event is raised just for visible rows, there would not be a performance issue even if you have too many rows. Anyway having a
DataGridViewwith too many rows is not a good idea and in such cases you should use a mechanism like virtualization or paging.Example
Regardless of number of records, here is an example which I colorize rows which their
FirstNamestarts with the text you entered inTextBox1if you pressButton1. If you enter empty string inTextBox1and pressButton1all rows will be shown in black.To make the example working you need to have a
DataGridView1,TextBox1andButton1on form.Note
If you apply
RowFilterto the data table which you set asDataSourceofDataGridView, it shows just filtered rows. So I didn't used it because you want to colorize filtered rows in red and others in black, so we need to show all rows.