Nico
Nico

Reputation: 237

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.

Upvotes: 6

Views: 31909

Answers (2)

Rubysmita Seth
Rubysmita Seth

Reputation: 21

I was originally getting this error (my C# code

someobject.TotalItemCount = (Int32)dbManager.GetParameterValue("TotalRows"))

where TotalItemCount was of int type, even though the SP was fine & was giving proper result. I got rid of this just by fixing the SP by adding the following code

Set @TotalRows =  @@rowcount.  

Upvotes: 0

SLaks
SLaks

Reputation: 888167

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.

Upvotes: 11

Related Questions