I'm trying to pass a CommandArgument
as int
to my stored procedure, but I get:
我正在尝试将CommandArgument作为int传递给我的存储过程,但我得到:
Failed to convert parameter value from a String to a Int32
无法将参数值从String转换为Int32
Even when it is converted before I pass it...
即使它在我通过它之前被转换了......
C# Code:
C#代码:
cmd.CommandText = "deleteProd";
int delprodID = Convert.ToInt32(e.CommandArgument.ToString());
Response.Write(delprodID);
cmd.Parameters.Add(new SqlParameter("@prodID", SqlDbType.Int)).Value = delprodID;
cmd.CommandType = CommandType.StoredProcedure;
sqlTools.cmdToNonQuery(cmd)
My Response.Write
shows that I've got the right ID in delprodID
.
我的Response.Write显示我在delprodID中有正确的ID。
Stored procedure:
存储过程:
ALTER PROCEDURE dbo.deleteProd @prodID int
AS
IF @prodID > 0
BEGIN
DELETE FROM products WHERE prodID = @prodID
END
2 个解决方案
#1
2
I had the same problem 3 months ago and couldn't explain what was going on. Somehow, you must explicitly declare parameter, set it and then add it to the Parameters property. It was only happening on SQL Server, not on Access for instance. I know that this is basically the same code but this worked for me, don't ask me why:
3个月前我遇到了同样的问题,无法解释发生了什么。不知何故,您必须显式声明参数,设置它然后将其添加到Parameters属性。它只发生在SQL Server上,而不是发生在Access上。我知道这基本上是相同的代码,但这对我有用,不要问我为什么:
SqlParameter param = new SqlParameter("@prodID", SqlDbType.Int);
param.Value = delprodID;
cmd.Parameters.Add(param);
#2
1
Try using SqlParameterCollection.AddWithValue Method It will greatly simplify things.
尝试使用SqlParameterCollection.AddWithValue方法它将大大简化事情。
cmd.CommandText = "deleteProd";
int delprodID = Convert.ToInt32(e.CommandArgument.ToString());
Response.Write(delprodID);
cmd.Parameters.AddWithValue("@prodID", delprodID);
cmd.CommandType = CommandType.StoredProcedure;
sqlTools.cmdToNonQuery(cmd)
#1
2
I had the same problem 3 months ago and couldn't explain what was going on. Somehow, you must explicitly declare parameter, set it and then add it to the Parameters property. It was only happening on SQL Server, not on Access for instance. I know that this is basically the same code but this worked for me, don't ask me why:
3个月前我遇到了同样的问题,无法解释发生了什么。不知何故,您必须显式声明参数,设置它然后将其添加到Parameters属性。它只发生在SQL Server上,而不是发生在Access上。我知道这基本上是相同的代码,但这对我有用,不要问我为什么:
SqlParameter param = new SqlParameter("@prodID", SqlDbType.Int);
param.Value = delprodID;
cmd.Parameters.Add(param);
#2
1
Try using SqlParameterCollection.AddWithValue Method It will greatly simplify things.
尝试使用SqlParameterCollection.AddWithValue方法它将大大简化事情。
cmd.CommandText = "deleteProd";
int delprodID = Convert.ToInt32(e.CommandArgument.ToString());
Response.Write(delprodID);
cmd.Parameters.AddWithValue("@prodID", delprodID);
cmd.CommandType = CommandType.StoredProcedure;
sqlTools.cmdToNonQuery(cmd)