指定的强制转换无效

本文关键字:转换 无效 | 更新日期: 2023-09-27 17:57:09

我正在尝试使用以下代码从我的数据库中获取Score_Waarde值:

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();

当我尝试运行它时,出现以下错误:指定的强制转换无效。我不明白为什么我会收到此错误,因为critiduserid给出了正确的值。

指定的强制转换无效

您的 SQL 可能返回不同的数字类型,例如 longdecimal ,或者显然是string

呼叫Convert.ToInt32 ,它没有开箱演员的限制。

我最初收到此错误(我的 C# 代码

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

其中TotalItemCount属于int类型,即使SP很好并且给出了正确的结果。我只是通过添加以下代码修复 SP 来摆脱这种情况

Set @TotalRows =  @@rowcount.