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
if(rdr["quantity"].GetType() != typeof(int))
throw new InvalidOperationException(
"quantity is a " + rdr["quantity"].GetType());
int number = (int)rdr["quantity"]; // error is here
Have you tried
int number=convert.toint16(rdr["quantity"]);
I bet quantity
is NULL
, which is not an integer.
Silly suggestion, maybe - but have you considered trying this - grab the result from your SqlDataReader
as an instance of object
and then checking what type it is? No one can tell you better what it really is than the CLR type system! :-)
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
object obj = rdr["quantity"];
if(obj != null)
{
string objType = obj.GetType().FullName;
}
}
}
If you do get a value back, you can check what type it is and hopefully convert it accordingly, depending on your results.
sl_id = Convert.ToInt32(lblintroducerid.Text.ToString());
sl_rank = Convert.ToInt32(lblassorank.Text.ToString());
Try one of the two options.
int number = rdr.getInt32(rdr.GetOrdinal("quantity"));
or
int number = int.parse(rdr["quantity"].ToString());