Azfar Azfar - 1 year ago 153
ASP.NET (C#) Question

Exception | must declare scalar variable @IdAlbum

I am getting an error "must declare scalar variable @IdAlbum". I have already been through similar posts on this topic but it does not help. Can someone have a look at the code below? When i use command paramters it gives me error. If I do not use command parameters, it works fine. I have put comments in the code to highlight where the problem is.

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


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

Answer Source

Look at this:

You are doing it wrong, you should use DataAdapter to fill missing parameters.

Look also at this question and answer, it provides good explanation: c# Using Parameters.AddWithValue in SqlDataAdapter

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download