Coloring Datagridview with C # Comparison

0

I would like to know if you have any way to color the row in the datagridview without using a loop.

I have a minimum stock and when available is below the minimum I would paint the red line.

Ididitthatway,butitgotreallyslow.

for(inti=0;i<dgvEstoque_pecas.RowCount-1;i++){intdisponivel=0,minimo=0;if(dgvEstoque_pecas.Rows[i].Cells["disponivel"].Value.ToString() != "")
    {
        disponivel = Convert.ToInt32(dgvEstoque_pecas.Rows[i].Cells[disponivel].Value.ToString());
    }
    else
    {
        disponivel = 0;
    }
    if (dgvEstoque_pecas.Rows[i].Cells["minimo"].Value.ToString() != "")
    {
        minimo = Convert.ToInt32(dgvEstoque_pecas.Rows[i].Cells["minimo"].Value.ToString());
    }
    else
    {
        minimo = 0;
    }

    if (disponivel < minimo)
        dgvEstoque_pecas.Rows[i].DefaultCellStyle.BackColor = Color.Red;

}
    
asked by anonymous 20.06.2018 / 20:34

1 answer

1

You can use the CellFormatting event that will be executed before the rendering of your DataGridView on the screen during DataBind() .

private void dgvEstoque_pecas_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{

    DataGridViewRow row = dgvEstoque_pecas.Rows[e.RowIndex];
    var cellDisponivel = e.Value;

    int disponivel = 0, minimo = 0;

    if (row.Cells["disponivel"].Value.ToString() != "")
    {
        disponivel = Convert.ToInt32(row.Cells[disponivel].Value.ToString());
    }
    else
    {
        disponivel = 0;
    }

    if (row.Cells["minimo"].Value.ToString() != "")
    {
        minimo = Convert.ToInt32(row.Cells["minimo"].Value.ToString());
    }
    else
    {
        minimo = 0;
    }

    if (disponivel < minimo)
        row.DefaultCellStyle.BackColor = Color.Red;

}

To add the event to your grid you can do it directly through the properties panel.

Or if you just copied and pasted the above code, you can directly link to InitiliazeComponent() in your *.Designer.cs .

this.dgvEstoque_pecas.CellFormatting += new System.Windows.Forms.DataGridViewCellFormattingEventHandler(this.dgvEstoque_pecas_CellFormatting);
    
21.06.2018 / 14:58