user1916528 user1916528 - 1 year ago 93
SQL Question

How to set SelectParameter in code behind in Asp.net web forms application?

I keep getting the error, Must declare the scalar variable "@inspIdFk" when attempting to use the following:

protected void rgInspections_SelectedIndexChanged(object sender, EventArgs e)
{
foreach (GridDataItem item in rgInspections.SelectedItems)
{
hdn_insp_id_pk.Value = item["inspIdPk"].Text;
}

string inspidvalue = hdn_insp_id_pk.Value;

if (HttpContext.Current.User.IsInRole("AKOB") || (HttpContext.Current.User.IsInRole("aMgr")))
{
SqlDataSource sdcRgActExps2 = new SqlDataSource();
sdcRgActExps2.ID = "sdcRgActExps2";
this.Page.Controls.Add(sdcRgActExps2);
sdcRgActExps2.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
sdcRgActExps2.SelectCommand = "SELECT ae.actExpIdPk, ae.inspIdFk, ae.actExpDt, aet.actExpType, ae.actExpQty, ae.actExpRate, ae.actExpBill, (ae.actExpQty * ae.actExpRate) AS subTotal FROM inspActExps ae LEFT JOIN actExpTypes aet ON ae.actExpType = aet.actExpTypeIdPk WHERE ([inspIdFk] = @inspIdFk) AND actExpSecCd = 1 ORDER BY actExpDt";
sdcRgActExps2.SelectParameters.Add("@inspIdFk", inspidvalue);
rgActExps2.DataSource = sdcRgActExps2;
rgActExps2.DataBind();
}
else
{
...
}
}


How can I successfully set the value of @inspIdFk? I verified that the query does pull data by removing inspIdFk = @inspIdFk from the WHERE clause.

Answer Source

As I understand it, SqlDataSource.SelectParameters.Add takes a value without an ampersand, so your add should look like this:

sdcRgActExps2.SelectParameters.Add("inspIdFk", inspidvalue);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download