I\'m having a \"Specified cast is not valid\" error. Windows form application in C#. I\'m trying to retrieve a value from a table. The value is either a smallint, or a numer
Since you said that you know what the value should be because you created the database... Can you check that rdr["quantity"] has a value then run a try parse on it?
if(rdr["quantity"] != null) {
int? number = null;
if(int.TryParse(rdr["quantity"].ToString(), out number)) {
Console.WriteLine("Hurray, I have an int. Up vote Coov!");
}
}
Try using SqlDataReader's GetInt32()
rdr.GetInt32(rdr.GetOrdinal("quantity"));
rdr["quantity"]
is going to be a boxed something. If it is not an int
then you can not unbox it directly to an int
(which is what you are trying to do) as you have to first unbox it to the appropriate type (say, short
). But this is too cumbersome so for clarity you're better off saying
Convert.ToInt32(rdr["quantity"]);