Click to See Complete Forum and Search --> : CastException while reading data


srihariacha
July 14th, 2008, 11:31 PM
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

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!

dglienna
July 14th, 2008, 11:45 PM
The problem is this statement:

reader.GetDateTime(0)

try:

reader(0)

srihariacha
July 15th, 2008, 12:32 AM
no the error is:

reader.GetDateTime(2)

However thanks a lot for help!

cjard
July 18th, 2008, 05:38 AM
if youre on .net 2 you can make your life a lot easier by reading teh DW2 link in my signature