简体   繁体   中英

DatagridView: Color row based on cell value

I am exposing my problem... I would like to color the lines of the datagridview taking as reference the value of the column 'LOTTO' until it is the same alternating two colors to facilitate the reading.

在此处输入图像描述

as you can see they generally go from 4 to 4 but can vary. for this reason I want to check the 'LOTTO' values

ideas? thanks!!

I did this many times, in your case it's using function like this:

Private Sub PaintAccValues()
    Dim Col1 As Color = Color.Beige
    Dim Col2 As Color = Color.Aquamarine
    Dim aCol As Color = Col1

    If Me.dgv.Rows.Count > 0 Then
        Me.dgv.Rows(0).DefaultCellStyle.BackColor = aCol   ' color background of the first row
        Dim RowVal As String = Me.dgv.Rows(0).Cells("Lotto").Value
        For ir = 1 To Me.dgv.Rows.Count - 1  ' notice we're starting on the 2nd line!
            If RowVal = Me.dgv.Rows(ir).Cells("Lotto").Value Then  ' following rows are same
                ' do nothing
            Else ' following rows differ (at the given column 'Lotto')
                If aCol = Col1 Then        ' change colors
                    aCol = Col2
                Else
                    aCol = Col1
                End If
            End If
            Me.dgv.Rows(ir).DefaultCellStyle.BackColor = aCol   ' color a row's background
            RowVal = Me.dgv.Rows(ir).Cells("Lotto").Value       ' set new actual value for a next row comparison
        Next
    End If
End Sub

You would simply call it:

Call PaintAccValues()

in some convenient place, it could be DataBindingComplete() , event for instance.

Obvously, I don't know how your DataGridView is named, or your columns (you didn't provide any code). You can modify it to color only some cells, etc. Or you can add parameters (DataGridViewName and ColumnName or ColumnIndex) and make it work with any DataGridView .

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