UPGRAYEDD
UPGRAYEDD

Reputation: 435

Conditional DataGrid formatting Colors

Ive got a Datagrid populated from a datatable. I want to change the display font color for an entire row where the 5th column's (Column Name in SQL = DDLS_Num) value is greater than 3.

Using conn As SqlConnection = New SqlConnection(ConnectionString)
            conn.Open()
            Using comm As SqlCommand = New SqlCommand(sqlquery, conn)
                Dim rs As SqlDataReader = comm.ExecuteReader
                Dim dt As DataTable = New DataTable
                dt.Load(rs)
                datgDXLog.DataSource = dt
                ' If the 5th column's [or column name] value is >=3 Then
                ' DataGridView1.Rows[5] [OR COLUMN NAME?] .DefaultCellStyle.ForeColor = Color.Red
                ' EndIF

            End Using 'comm
        End Using 'conn

Upvotes: 0

Views: 158

Answers (2)

matzone
matzone

Reputation: 5719

I think you have to do that in RowPrepaint event ..

Private Sub DataGridView1_RowPrePaint(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewRowPrePaintEventArgs) Handles DataGridView1.RowPrePaint
    If DataGridView1.Rows(e.RowIndex).Cells(5).Value >= 3 Then
        DataGridView1.Rows(e.RowIndex).DefaultCellStyle.ForeColor = Color.Red
    End If
End Sub

Upvotes: 2

NoAlias
NoAlias

Reputation: 9193

Handle the coloring in the DataGridView.RowDataBound Event:

Public Sub DataGridView1_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs) Handles DataGridView1.RowDataBound

    If e.Row.RowType = DataControlRowType.DataRow Then

        If IsNumeric(e.Row.Cells(4).Text) AndAlso CDbl(e.Row.Cells(4).Text) > 3 Then

            e.Row.ForeColor = System.Drawing.Color.Red

        End If 

    End If

End Sub

Upvotes: 0

Related Questions