tags:

views:

178

answers:

2

I'm trying to pull data using a SqlDataReader, one column of which is in datetime. I'd like to do something like this

SqlCommand command = new SqlCommand("SELECT * FROM table", connection); //connection is defined earlier
        SqlDataReader data = command.ExecuteReader();
        while(data.Read()){
             DateTime birthday = data["Birth"];
             list.Add(birthday);
        }
    }

Can I do this? Or does SqlDataReader return strings, in which case I'd have to create a new DateTime object using that string?

Thanks, -S

+7  A: 

SqlDataReader returns data as strongly-typed objects - just call the right method, e.g.:

data.GetDateTime(ordinal)

Joe Albahari
+4  A: 

You want:

DateTime birthday = data.GetDateTime(data.GetOrdinal("Birth"));

SqlDataReader has a whole bunch of strongly-typed Get*() methods.

Matt Hamilton
The GetDateTime method only takes an ordinal, not a column name, so that'd need to be data.GetDateTime(data.GetOrdinal("Birth"))
LukeH
Indeed you are right! Fixing now.
Matt Hamilton