简体   繁体   中英

DataGridView: How to change cell color depending on data source value

If my dataset has the following records

Col1 Col2 Col3
A    D    H 
B    E    I
C    F    J

I want to highlight the cells where values are either C,E,F. The highlight should happen during assign of datasource to DataGridView. Tried CellValueChanged event, but can't make it achieve what I want to do.

I hope not to go iterate each cell and validate the value.

Doable?

TIA!

I've not used CellFormatting or CellPainting much but I think that, in this case, CellFormatting might be the better option. This example worked for me:

Private Sub DataGridView1_CellFormatting(sender As Object, e As DataGridViewCellFormattingEventArgs) Handles DataGridView1.CellFormatting
    Dim cell = DataGridView1(e.ColumnIndex, e.RowIndex)

    Select Case TryCast(cell.Value, String)
        Case "C", "E", "F"
            e.CellStyle.BackColor = Color.Red
    End Select
End Sub

CellFormatting is raised per cell, every time a cell needs formatting. That means that, unlike CellValueChanged , it will be raised when the cell is initially created.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM