1 Replies - 4379 Views - Last Post: 13 December 2015 - 09:15 AM

#1 andrewsw  Icon User is online

  • blow up my boots
  • member icon

Reputation: 6440
  • View blog
  • Posts: 26,055
  • Joined: 12-December 12

DataGridView Conditional Formatting

Posted 13 December 2015 - 08:58 AM

We can use the CellFormatting event to conditionally format - to colour-code - cells of a DataGridView.
    Private Sub dgvExcel_CellFormatting(sender As Object, e As DataGridViewCellFormattingEventArgs) Handles dgvExcel.CellFormatting
        If e.ColumnIndex = dgvExcel.Columns("Salary").Index Then
            If Not IsDBNull(e.Value) AndAlso Convert.ToDecimal(e.Value) > 24000 Then
                e.CellStyle.BackColor = Color.Aquamarine
            End If
        End If
    End Sub

(I added to my other snippet, Populate DataGridView With Excel Data.)

Attached Image

The parameter e gives us the ColumnIndex and RowIndex of the current cell. e.CellStyle allows us to format the BackColor, ForeColor, Font, etc..

Similar examples can be found. One thing that distinguishes mine is the use of IsDBNull() to ignore blank cells.

It is also possible to format the cells as currency:
e.CellStyle.Format = "c" 'or
e.CellStyle.Format = "#,###"

although this is typically achieved for the column using DefaultCellStyle.Format.

A fuller example:

How to: Customize Data Formatting in the Windows Forms DataGridView Control

Is This A Good Question/Topic? 0
  • +

Replies To: DataGridView Conditional Formatting

#2 andrewsw  Icon User is online

  • blow up my boots
  • member icon

Reputation: 6440
  • View blog
  • Posts: 26,055
  • Joined: 12-December 12

Re: DataGridView Conditional Formatting

Posted 13 December 2015 - 09:15 AM

For anyone interested, I used the form's load event to change the formatting of the column headers:
    Private Sub frmExcel_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        dgvExcel.EnableHeadersVisualStyles = False

        dgvExcel.ColumnHeadersDefaultCellStyle = New DataGridViewCellStyle With {
            .Font = New Font(dgvExcel.Font, FontStyle.Bold),
            .ForeColor = Color.Red
        }
    End Sub

This post has been edited by andrewsw: 13 December 2015 - 09:16 AM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1