Compare date field with current date in datagridviwer

Asked

Viewed 102 times

1

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

follows my code

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

2 answers

3

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 believe you answer what you wish.

  • 1

    Thank you so much for the help...tested and also worked your response.

0


Convert the cell value to Datetime, and then make the comparison:

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

obs. If the cell is empty, null, or in an incorrect format, an error will occur in Parse. You may need to deal with this problem.

Edit: Treating 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;
    }
}
  • Really Rovann in most cases this field gets blank, how can I treat it in my code, could you explain to me?

  • @Juniorguerreiro changed the code, see if everything goes well

  • Rovann I took the test here the way you told me before you changed the code and there was no error in the parse no, but I’ll try this way you passed me too.

  • better do treating... .Value for null, it’s about to be object not reference to an instance, and if it is not null and the string is not a date, it will give a seqüência de entrada não estava em um formato incorreto

  • I tested both answers and they both worked perfectly. Thank you very much for your help

Browser other questions tagged

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