Nico Nico - 3 months ago 12
SQL Question

Specified cast is not valid

I'm trying to get the

Score_Waarde
value from my database using the following code :

critid = critid_arr[teller2].ToString();

int scorehulp = 0;
string userid = Session["userid"].ToString();

SqlCommand cmd3 = new SqlCommand("SELECT Score_Waarde FROM Score WHERE Crit_ID = '" + critid + "' AND User_ID = '" + userid + "' ", con);
scorehulp = (int)cmd3.ExecuteScalar();


When I try to run this I get the following error: Specified cast is not valid.
I don't understand why I'm getting this error because
critid
and
userid
are giving the correct values.

Answer

Your SQL is probably giving back a different numeric type, such as long or decimal, or, apparently, string.

Call Convert.ToInt32, which doesn't have the limitations of an unboxing cast.