CastException while reading data
Code:
using (SqlConnection con = new SqlConnection())
{
con.ConnectionString = "Data Source=.\\SQLEXPRESS;Initial Catalog=AdventureWorks;Integrated Security=True";
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select FirstName,LastName,ModifiedDate from Person.Contact order by Title;select * from HumanResources.Employee";
con.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
//Error triggered here
Console.WriteLine(" {0} {1} - {2,18:D}", reader["FirstName"], reader[1], reader.GetDateTime(0));
}
Console.WriteLine(Environment.NewLine);
reader.NextResult();
Console.WriteLine("Employee Table Metadata");
for (int field = 0; field < reader.FieldCount; field++)
{
Console.WriteLine("Column Name : {0} Type : {1}", reader.GetName(field), reader.GetDataTypeName(field));
}
}
}
and the error is:
InvalidCastException was unhandled
Specified cast is not valid
also I tried
Code:
Console.WriteLine(" {0} {1} - {2,18:D}", (string)reader["FirstName"].ToString(), (string)reader[1].ToString(), reader.GetDateTime(0));
it still showing me same error
Help me!
Re: CastException while reading data
The problem is this statement:
Code:
reader.GetDateTime(0)
try:
Re: CastException while reading data
no the error is:
Code:
reader.GetDateTime(2)
However thanks a lot for help!
Re: CastException while reading data
if youre on .net 2 you can make your life a lot easier by reading teh DW2 link in my signature