无法得到它!此SqlParameterCollection不包含带ParameterName的SqlParameter。存储过程参数

时间:2013-03-14 03:06:18

标签: c# asp.net stored-procedures

我知道这个问题已被多次提出,而且我已经阅读了很多答案,但我无法弄清楚出了什么问题。已经好几个小时了。任何帮助都会受到赞赏。我只是试图在ASP页面中调用存储过程,我无法正确添加参数,获得它不在集合中的异常。

我修改了我的proc,如下所示,试图简化并解决问题。

 ALTER PROCEDURE [dbo].[up_validateUserWithClinicCount]     
@HTID       INT = 0,
@ValidUserID    INT OUTPUT,
@MultiClinicFlag    INT OUTPUT
AS
DECLARE @vClinicCount   INT = null
DECLARE @vUserValid     INT = null
BEGIN

SET @ValidUserID = 2
SET @MultiClinicFlag = 1
END;

和C#代码

String connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["PC3PaymentConnection"].ConnectionString;
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            connection.Open();
            using (SqlCommand cmd = new SqlCommand("up_validateUserWithClinicCount", connection))
            {

                cmd.CommandType = CommandType.StoredProcedure;

                cmd.Parameters.AddWithValue("@HTID", htId);

                SqlParameter uidOut = new SqlParameter("@ValidUserID", SqlDbType.Int);
                uidOut.Size = 4;
                uidOut.Direction = ParameterDirection.Output;
                cmd.Parameters.Add(uidOut);

                SqlParameter pMultiClinics = new SqlParameter();
                pMultiClinics.ParameterName = "@MultiClinicFlag";
                pMultiClinics.SqlDbType = SqlDbType.Int;
                pMultiClinics.Direction = ParameterDirection.Output;
                cmd.Parameters.Add(pMultiClinics);

                try
                {
                    cmd.ExecuteNonQuery();
    //--> Error points to the next line, and I have tried to use int.parse rather than convert   also, with the same error -- parameter not in collection
                    MultiClinics = Convert.ToInt16(cmd.Parameters["pMultiClinics"].Value);
                    PC3User = Convert.ToInt16(uidOut.Value.ToString());
                }
                catch (SqlException sqlEx)
                {
                    LbMsg.ForeColor = System.Drawing.Color.Red;
                    LbMsg.Text = sqlEx.Message;
                }
            }
        }

谢谢,如果你能看到我错过的东西。

1 个答案:

答案 0 :(得分:2)

您已经拥有参数的对象引用,您无需从参数集合中获取它。另外,sql整数是32位。

MultiClinics = (int)pMultiClinics.Value;

要从参数集合中检索,请使用您提供的ParameterName:

MultiClinics = (int)cmd.Parameters["@MultiClinicFlag"].Value;