Compare date field with current date in datagridviwer

1

I have a field in my datagridiviwer that is called "PROGRAMMING" this field receives a date, which comes from the database as varchar or string, I need to compare the date that is in this field with the current date, if it is greater than the current date the date line datagridiviwer changes color. I did the command below but I am not getting the result that I hope, it is changing the color of all the lines.

follow my code

else if (row.Cells["PROGRAMAÇÃO"].Value.ToString() != Convert.ToString(DateTime.Now))
{
    row.DefaultCellStyle.BackColor = Color.Bisque;
}
    
asked by anonymous 16.10.2017 / 13:33

2 answers

0

Convert the cell value to DateTime, and then compare:

else if (DateTime.Parse(row.Cells["PROGRAMAÇÃO"].Value.ToString()) > DateTime.Now)
{
    row.DefaultCellStyle.BackColor = Color.Bisque;
}

Obs. If the cell is blank, null, or in an incorrect format, Parse error will occur. You may need to address this issue.

Edit: Addressing possible errors.

if (...)
{ 
    ...
}
else if (row.Cells["PROGRAMAÇÃO"].Value != null)
{
    DateTime programacao; //variavel auxiliar
    if (DateTime.TryParse(row.Cells["PROGRAMAÇÃO"].Value.ToString(), out programacao))
    {
        if (programacao > DateTime.Now)
            row.DefaultCellStyle.BackColor = Color.Bisque;
    }
}
    
16.10.2017 / 13:49
2

I would do something like this:

if (row.Cells["PROGRAMAÇÃO"].Value != null)
{
    DateTime dataProgramacao = DateTime.Parse(row.Cells["PROGRAMAÇÃO"].Value.ToString();
    DateTime dataAtual = DateTime.Now;
    int resultado = DateTime.Compare(dataProgramacao, dataAtual);

    if (resultado < 0)
    //dataProgramacao é menor que a dataAtual
    else if (resultado == 0)
     //datas iguais
    else
    //dataProgramacao é maior que a dataAtual
    //row.DefaultCellStyle.BackColor = Color.Bisque;
}

I think you get what you want.

    
16.10.2017 / 15:32