public static SqlParameter AddParameter(string parameterName,object value,SqlDbType DbType,int size)
{
SqlParameter param = new SqlParameter();
param.ParameterName = parameterName;
param.Value = value ?? (object)DBNull.Value;
param.SqlDbType = DbType;
param.Size = size;
param.Direction = ParameterDirection.Input;
return param;
}
public static DataTable ExecuteDTByProcedure(string ProcedureName ,SqlParameter[] Params)
{
SqlConnection con = new SqlConnection(ConnectionString);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = ProcedureName;
cmd.Parameters.AddRange(Params);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dtable = new DataTable();
try
{
sda.Fill(dtable);
}
catch (Exception ex)
{
}
finally
{
sda.Dispose();
cmd.Parameters.Clear();
cmd.Dispose();
con.Dispose();
}
return dtable;
}
}
}
错误:第43行:cmd.Connection = con; 第44行:cmd.CommandText = ProcedureName; 第45行:cmd.Parameters.AddRange(Params); 第46行: 第47行:
SqlParameterCollection只接受非null的SqlParameter类型对象。 参数名称:值
答案 0 :(得分:0)
我找到了解决方案。在SqlParameters数组中,我插入的索引号相同,因为它必须具有从0开始的索引
SqlParameter [] parameters = new SqlParameter [4];
parameters[0] = DataLayer.DataAccess.AddParameter("@ProductName",ProductName,System.Data.SqlDbType.VarChar, 300);
parameters[0] = DataLayer.DataAccess.AddParameter("@ProductDescription", ProductDescription, System.Data.SqlDbType.VarChar, 1000);
parameters[0] = DataLayer.DataAccess.AddParameter("@ProductPrice",ProductPrice,System.Data.SqlDbType.Int, 100);
parameters[0] = DataLayer.DataAccess.AddParameter("@ProductImage",ProductImage,System.Data.SqlDbType.VarChar,500);
DataTable dt = DataLayer.DataAccess.ExecuteDTByProcedure("Sp_AddNewProduct", parameters);
这是正确的代码:
SqlParameter [] parameters = new SqlParameter [4];
parameters[0] = DataLayer.DataAccess.AddParameter("@ProductName",ProductName,System.Data.SqlDbType.VarChar, 300);
parameters[1] = DataLayer.DataAccess.AddParameter("@ProductDescription", ProductDescription, System.Data.SqlDbType.VarChar, 1000);
parameters[2] = DataLayer.DataAccess.AddParameter("@ProductPrice",ProductPrice,System.Data.SqlDbType.Int, 100);
parameters[3] = DataLayer.DataAccess.AddParameter("@ProductImage",ProductImage,System.Data.SqlDbType.VarChar,500);
DataTable dt = DataLayer.DataAccess.ExecuteDTByProcedure("Sp_AddNewProduct", parameters);
注意"参数[]"
中的所有索引号都不为零