tags:

views:

66

answers:

3

I'm having problems when using linq on a datatable.asenumerable().
This throws InvalidCastException.

DateTime date=r.Field<DateTime>("date");

This works fine.

DateTime date = DateTime.Parse(r.Field<string>("date"));

What am I missing?

Regards Sven

A: 

Why would you expect it to work? The following code doesn't compile:

DateTime dt1 = (DateTime)"2004-01-01";

Whereas this does:

DateTime dt1 = DateTime.Parse("2004-01-01");

As in, you can't just cast a string to a DateTime, so if your value is a string, you need to explicitly convert it.

Damien_The_Unbeliever
When you put it like that it's quite obvious.Lack of experience and working brain I guess.Thanks a bunch!
Zwempha
A: 

Are you sure your "date" column is of type DateTime?

This test code works as expected:

        DataTable dt = new DataTable();

        dt.Columns.Add(new DataColumn("date", typeof(DateTime)));

        for (int i = 0; i < 10; i++)
        {
            DataRow row = dt.NewRow();
            row["date"] = DateTime.Now.AddDays(i);
            dt.Rows.Add(row);
        }

        foreach (var r in dt.AsEnumerable())
        {
            DateTime d = r.Field<DateTime>("date"); // no problems here!

            Console.Write(d.ToLongDateString());
        }
kristian
No the column is a string, my mistake.
Zwempha
A: 

Cast works between related types. string and date don't belong to same hierarchy & hence no direct translation is possible.

You can use cast, when you are sure that the types are related and conversion is possible.

Parse is different than cast.
i.e you are telling the runtime to see if it can be parsed to make a date out of it (per your example).

shahkalpesh