Change color line according to cell content in datagridview

Asked

Viewed 2,023 times

1

I have a Windows Form that carries a DataGridView, in it has a column that contains positive and negative values, need that when the value of this column is negative the row is a different color.

How can I do that?

follows the Code:

private void ListaGrid()
{
    string strSQL = @"SELECT  
            SA.A1_COD                     AS CODIGO,
            SA.A1_NOME                    AS CLIENTE,
            SA.A1_LC                      AS [LIMITE CREDITO],
            SUM(SE.E1_VALOR)              AS [TOTAL COMPRA],
            SUM(SE.E1_SALDO)              AS [SALDO ABERTO],
            SA.A1_LC - SUM(SE.E1_SALDO)   AS [SALDO LIMITE]
        FROM SA1010 AS SA
        INNER JOIN SE1010 AS SE WITH (NOLOCK) ON SA.A1_COD = SE.E1_CLIENTE
        WHERE SA.D_E_L_E_T_ <> '*' AND SE.D_E_L_E_T_ <> '*'
        GROUP BY SA.A1_COD, SA.A1_NOME, SA.A1_LC
        ORDER BY CODIGO";

    comando = new SqlCommand(strSQL, conm);

    try
    {
        SqlDataAdapter dados = new SqlDataAdapter(comando);
        DataTable dtLista = new DataTable();
        dados.Fill(dtLista);

        DGW_LimiteCredito.DataSource = dtLista;
    }
    catch
    {
        MessageBox.Show("Não existem dados a serem encontrados");
    }
}

1 answer

3


You will iterate through all the lines of your DataGridView and compare the value of the column that contains the value you want to check. If the value is negative, the line (Row) will be painted of the color you choose, in the example is red.

foreach (DataGridViewRow row in DGW_LimiteCredito.Rows)
{
     if (Convert.ToInt32(row.Cells[/*Index ou nome da coluna com o valor*/].Value) < 0 ) 
     {
         // Se for negativo, fica vermelho
         row.DefaultCellStyle.BackColor = Color.Red; 
     }
}
  • 1

    While it’s readable what you’ve done, consider leaving an explanation.

  • @LP.Gonçalves It’s true, I left explained.

  • Thank you very much gave it right here.

Browser other questions tagged

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