hi there,
i have a datagrid view in a form and i have a calender control in one of the cells.

when i try to validate it it gives an invalidCastException.(the line is bolded, this is tha place where the error occurs)

private void dgvActions_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            if (e.ColumnIndex == 2)
            {
                if (e.FormattedValue != null)
                {
                    DateTime TodayDate = System.DateTime.Now.Date;
                    [B]DateTime Duedate = (DateTime)e.FormattedValue;[/B]

                    if (Duedate < TodayDate)
                        MessageBox.Show("invalid");

                }
            }
        }

how can i solve this.

thankxxxxx

when i try to validate it it gives an invalidCastException.(the line is bolded, this is tha place where the error occurs)

...

how can i solve this.

Rephrasing your question: "Why isn't e.FormattedValue a DateTime ?"

A good next step is to figure out what type of object it really is. Try something like this:

private void dgvActions_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
  if (e.ColumnIndex == 2)
  {
    if (e.FormattedValue != null)
    {
      MessageBox.Show(e.FormattedValue.GetType().FullName);
    }
  }
}

Once you know what type e.FormattedValue really is, your new question can be: "Why is e.FormattedValue this type?" With luck, knowing what type it is will give you some idea of where it came from.

Comments
Good thinking!

Rephrasing your question: "Why isn't e.FormattedValue a DateTime ?"

A good next step is to figure out what type of object it really is. Try something like this:

private void dgvActions_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
  if (e.ColumnIndex == 2)
  {
    if (e.FormattedValue != null)
    {
      MessageBox.Show(e.FormattedValue.GetType().FullName);
    }
  }
}

Once you know what type e.FormattedValue really is, your new question can be: "Why is e.FormattedValue this type?" With luck, knowing what type it is will give you some idea of where it came from.

hey i know it is string that is why i try to convert it to datetime
by the code below.
it gives an error

i won't get it

thankxxxxxxxx

Since the purpose of the CellValidating event is to confirm that the text entered by a user is in the valid format, your first test (after != null) should perhaps be to use DateTime.TryParse to test if the entered value is in fact a date.

This article has been dead for over six months. Start a new discussion instead.