Colorize Datagridview with comparison C#

Asked

Viewed 179 times

0

I wonder if there is any way to color datagridview line without using a loop.

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

inserir a descrição da imagem aqui

I did it that way, but it got too slow.

for (int i = 0; i < dgvEstoque_pecas.RowCount - 1; i++)
{
    int disponivel = 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;

}
  • Search by Rowdatabound, it is a Web or Desktop project?

  • It’s a Windows Forms, Desktop project.

  • So you don’t have Rowdatabound, you can try for Cellformatting

  • try something like this, DataGridViewCell cell = new DataGridViewTextBoxCell();&#xA;&#xA; cell.Style.BackColor = Color.Wheat; this can also help ************https://msdn.microsoft.com/pt-br/library/system.windows.datagridviewcellstyle(v=vs.110). aspx

1 answer

1


You can use the event CellFormatting who will be executed before the surrender of his DataGridView on the screen during the 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 from the properties panel.

inserir a descrição da imagem aqui

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

this.dgvEstoque_pecas.CellFormatting += new System.Windows.Forms.DataGridViewCellFormattingEventHandler(this.dgvEstoque_pecas_CellFormatting);
  • Thanks for the help Leandro, it worked perfectly and got much faster.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.