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.

commented: Good thinking! +6

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.

hey i know it is string

Ah. Wasn't sure if you knew the type; that's why I started where I did.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.