异常 |必须声明标量变量@IdAlbum

Exception | must declare scalar variable @IdAlbum

我遇到错误 "must declare scalar variable @IdAlbum"。我已经浏览过有关此主题的类似帖子,但没有帮助。有人可以看看下面的代码吗?当我使用命令参数时,它给我错误。如果我不使用命令参数,它工作正常。我在代码中添加了注释以突出显示问题所在。

 public DataSet databind ()
    {
        DataSet ds = new DataSet();
        string con_str = ConfigurationManager.ConnectionStrings["con_nc"].ConnectionString;
        SqlConnection con = new SqlConnection(con_str);
        try
        {

            con.Open();

            string albumId = Request.QueryString["AlbumId"].Trim();
            this.albumName = Request.QueryString["AlbumName"];

            //getting the count of the pictures from DB and assigning it to pagesize so that all pictures of single album come in 1 page only.

            string photoCountQuery = "select count(*) from gallery_photos where AlbumId=@albumId"; // THIS WORKS FINE


            SqlCommand picCount = new SqlCommand(photoCountQuery, con);// THIS WORKS FINE
            picCount.Parameters.AddWithValue("@albumID", albumId);// THIS WORKS FINE
            int photoCount = Convert.ToInt16(picCount.ExecuteScalar());// THIS WORKS FINE

            int start = (int)ViewState["start"];// THIS WORKS FINE
            ViewState["pagesize"] = photoCount;// THIS WORKS FINE

            //string query = "select * from gallery_photos where AlbumId='" + albumId + "'"; //// THIS WORKS FINE
            string query = "select * from gallery_photos where AlbumId=@IdAlbum";// THIS is the problem. It does not work when i use command paramters
            SqlCommand cmd = new SqlCommand(query, con);
            cmd.Parameters.AddWithValue("@IdAlbum", albumId);
            SqlDataAdapter da = new SqlDataAdapter(query, con);

            da.Fill(ds, start, (int)(ViewState["pagesize"]), "gallery_photos");


        }
        catch (Exception ex)
        {
            ExceptionUtility.LogException(ex, "Exception in " + Path.GetFileName(Page.AppRelativeVirtualPath).ToString());
            Context.ApplicationInstance.CompleteRequest();
        }
        finally
        {
            con.Close();
        }
        return ds;
    }

看看这个:https://msdn.microsoft.com/en-us/library/ebxy9a8b(v=vs.80).aspx

你做错了,你应该使用DataAdapter来填充缺少的参数。

也看看这个问答,它提供了很好的解释:c# Using Parameters.AddWithValue in SqlDataAdapter