Conditional formatting on a gridView

Asked

Viewed 634 times

2

I have a gridView where it’s loaded, from my SQLServer, all bank information.

My question is this. can change the color of the source when a date is less than the date of the system (for example, put in red the accounts that are past due)?

Follow my code to load the gridView and the screen:

private void CarregarGridContasPagarAberto()
{

    IList<ContasPagarDTO> listaContasPagar = new List<ContasPagarDTO>();
    listaContasPagar = new ContasPagarModel().CargaContasPagarAberto();

    dgvContasPagar.AutoGenerateColumns = false;
    dgvContasPagar.DataSource = listaContasPagar;
}

screen:

Grid

private void dgvContasPagar_CellFormatting(object sender, DataGridViewCellFormattingEventArgs Arguments)
{
    IList<ContasPagarDTO> listaContasPagar = new List<ContasPagarDTO>();
    listaContasPagar = new ContasPagarModel().CargaContasPagarAberto();

    if (this.dgvContasPagar.Columns[Arguments.ColumnIndex].Name == "DtVencContas")
    {
       // return;

       var Conta = listaContasPagar[Arguments.RowIndex];

       if(Conta.DtVencContas < DateTime.Now)
           Arguments.CellStyle.ForeColor = Color.Red;
       else
           Arguments.CellStyle.ForeColor = Color.Black;
    }
}

Resultado do Grid

1 answer

1


Use the Cellformating event.

private void DataGridView1_CellFormatting (object Sender, DataGridViewCellFormattingEventArgs Arguments)
{
    if (this.DataGridView1.Columns [Arguments.ColumnIndex].Name != "Sua Coluna Aqui")
        return;

    var Conta = ListaContasPagar [Arguments.RowIndex];

    if (DateTime.Now < Conta.DataDaConta)
        Arguments.CellStyle.BackColor = Color.Green;
    else
        Arguments.CellStyle.BackColor = Color.Red;
}
  • I edited my question with error see if anything was missing

  • Set "Datagridviewcellformattingeventargs and" to "Datagridviewcellformattingeventargs Arguments".

  • Failed to change color and error Additional information: Cannot convert an object of type 'System.Windows.Forms.Datagridviewtextboxcolumn' in type 'System.Iconvertible'.

  • You are trying to convert the column (being that it is an object but not the value) to datetime in the if condition, notice that I created the variable Account to get the cell value, use this variable to compare the date.

  • 1

    Thank you Alexandre helped me D+, I edited my question with the code and the result screen -

Browser other questions tagged

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