Saltar al contenido

Formato Condicional a Celdas/Columnas de DataGridView con C# y VB.Net

Hola, en el tutorial anterior personalizamos un DataGridView, ahora aplicaremos formato condicional a una Columna-Celdas para mostrar los productos en bajo stock en color rojo de Alerta, mostrar una marca de un color determinado, también es muy usado para mostrar notas académicas, entre otras. El Formato Condicional se usa muy a menudo en las hojas de cálculo de Excel.

Bien, empecemos con tutorial:

PD: Este es un tutorial actualizado del Video tutorial de YouTube.

Mostrar de Color Rojo los Productos en Bajo Stock (Celda-Columna)

Cambiaremos el color de fondo y el color del texto de las celdas en la columna Stock u cualquier columna con valores numéricos del Datagridview, para este ejercicio usaré el proyecto CRUD con Arquitectura en Capas y POO Nivel Base.

1. Crear evento CellFormatting

En la pestaña de eventos de las propiedades del DataGridView, buscamos el evento CellFormatting, sobre ello, haga Doble Clic para crear el evento. Este evento nos permite dar formato al contenido a las Celdas-Columnas. El método del evento de debió haber quedado de esta manera:

private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
}

2. Codificar

  • Creamos una condición para obtener el índice de la columna del Datagridview, el nombre de la columna debe ser igual como está escrita en la base de datos, o igual al nombre de la columna que asignó manualmente al crear las columnas, o también puede ser igual al número de posición: if (this.dataGridView1.Columns[e.ColumnIndex].Name == “Stock”)
  • Creamos otra condición para no aplicar el formato a valores nulos del DGV, esto para evitar errores (como sucedió en el video tutorial): if (e.Value != null)
  • También creamos otra condición para no aplicar el formato a valores nulos devueltos desde la base de datos, de igual manera para evitar errores: if (e.Value.GetType() != typeof(System.DBNull))
  • Por último, aplicamos el formato que deseemos a cualquier columna, en este caso la columna stock, puedes cambiar el formato a cuan Datos/Condiciones desees. Por ejemplo, yo aplicare formato condicional para pintar de naranja a stock de productos menores a 20 (if (Convert.ToInt32(e.Value) <= 20)), y pintar de rojo a stock de productos menores a 10 (if (Convert.ToInt32(e.Value) <= 10)). Y así sucesivamente puedes agregar formato a cualquier valor.

El código completo te debería quedar de estar manera:

private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    if (this.dataGridView1.Columns[e.ColumnIndex].Name == "Stock")
    {
        if (e.Value != null)
        {
            if (e.Value.GetType() != typeof(System.DBNull))
            {
                //Stock menor a 20
                if (Convert.ToInt32(e.Value) <= 20)
                {
                    e.CellStyle.BackColor = Color.LightSalmon;
                    e.CellStyle.ForeColor = Color.Red;
                }

                //Stock menor a 10
                if (Convert.ToInt32(e.Value) <= 10)
                {
                    e.CellStyle.BackColor = Color.Salmon;
                    e.CellStyle.ForeColor = Color.Red;
                }
            }

        }
    }
}
Private Sub DataGridView1_CellFormatting(sender As Object, e As DataGridViewCellFormattingEventArgs) Handles DataGridView1.CellFormatting

    If Me.DataGridView1.Columns(e.ColumnIndex).Name = "Stock" Then

        If e.Value IsNot Nothing Then

            If e.Value.[GetType]() <> GetType(System.DBNull) Then

                'Stock menor a 20'
                If Convert.ToInt32(e.Value) <= 20 Then
                    e.CellStyle.BackColor = Color.LightSalmon
                    e.CellStyle.ForeColor = Color.Red
                End If

                'Stock menor a 10'
                If Convert.ToInt32(e.Value) <= 10 Then
                    e.CellStyle.BackColor = Color.Salmon
                    e.CellStyle.ForeColor = Color.Red
                End If
            End If
        End If
    End If

End Sub

Mostrar de Color una marca determinada (Celda-Columna)

De igual manera que lo anterior, podemos aplicar formato condicional a valores en cadena (Texto), en esta ocasión cambiaré de color del texto de la celada en la  columna Marca u cualquier columna con valores en cadena del Datagridview.

private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{ 
    if (this.dataGridView1.Columns[e.ColumnIndex].Name == "Marca")
    {
        if (e.Value != null)
        {
            if (e.Value.GetType() != typeof(System.DBNull))
            {
                if (e.Value.ToString() =="iberica")
                {
                    e.CellStyle.ForeColor = Color.SeaGreen;
                }

                if (e.Value.ToString() == "marcacola")
                {
                    e.CellStyle.ForeColor = Color.SteelBlue;
                }
            }
        }
    }
}
Private Sub DataGridView1_CellFormatting(sender As Object, e As DataGridViewCellFormattingEventArgs) Handles DataGridView1.CellFormatting

    If Me.DataGridView1.Columns(e.ColumnIndex).Name = "Marca" Then

        If e.Value IsNot Nothing Then

            If e.Value.[GetType]() <> GetType(System.DBNull) Then

                If e.Value.ToString() = "iberica" Then
                    e.CellStyle.ForeColor = Color.SeaGreen
                End If

                If e.Value.ToString() = "marcacola" Then
                    e.CellStyle.ForeColor = Color.SteelBlue
                End If
            End If
        End If
    End If

End Sub

Aplicar formato condicional a varias columnas

Puedes aplicar formato condicional a varias columnas en el mismo método del evento CellFormatting, por ejemplo, formato a la columna stock y marcas de los ejemplo anteriores:

private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    if (this.dataGridView1.Columns[e.ColumnIndex].Name == "Stock")
    {
        if (e.Value != null)
        {
            if (e.Value.GetType() != typeof(System.DBNull))
            {
                //Stock menor a 20
                if (Convert.ToInt32(e.Value) <= 20)
                {
                    e.CellStyle.BackColor = Color.LightSalmon;
                    e.CellStyle.ForeColor = Color.Red;
                }

                //Stock menor a 10
                if (Convert.ToInt32(e.Value) <= 10)
                {
                    e.CellStyle.BackColor = Color.Salmon;
                    e.CellStyle.ForeColor = Color.Red;
                }
            }

        }
    }

    if (this.dataGridView1.Columns[e.ColumnIndex].Name == "Marca")
    {
        if (e.Value != null)
        {
            if (e.Value.GetType() != typeof(System.DBNull))
            {
                if (e.Value.ToString() =="iberica")
                {
                    e.CellStyle.ForeColor = Color.SeaGreen;
                }

                if (e.Value.ToString() == "marcacola")
                {
                    e.CellStyle.ForeColor = Color.SteelBlue;
                }
            }
        }
    }
}
Private Sub DataGridView1_CellFormatting(sender As Object, e As DataGridViewCellFormattingEventArgs) Handles DataGridView1.CellFormatting

    If Me.DataGridView1.Columns(e.ColumnIndex).Name = "Stock" Then

        If e.Value IsNot Nothing Then

            If e.Value.[GetType]() <> GetType(System.DBNull) Then
                'Stock menor a 20
                If Convert.ToInt32(e.Value) <= 20 Then
                    e.CellStyle.BackColor = Color.LightSalmon
                    e.CellStyle.ForeColor = Color.Red
                End If

                'Stock menor a 10
                If Convert.ToInt32(e.Value) <= 10 Then
                    e.CellStyle.BackColor = Color.Salmon
                    e.CellStyle.ForeColor = Color.Red
                End If
            End If
        End If
    End If

    If Me.DataGridView1.Columns(e.ColumnIndex).Name = "Marca" Then

        If e.Value IsNot Nothing Then

            If e.Value.[GetType]() <> GetType(System.DBNull) Then

                If e.Value.ToString() = "iberica" Then
                    e.CellStyle.ForeColor = Color.SeaGreen
                End If

                If e.Value.ToString() = "marcacola" Then
                    e.CellStyle.ForeColor = Color.SteelBlue
                End If
            End If
        End If
    End If
End Sub

Resultado:

Video Tutorial