如何在Asp.net Web表单应用程序中的代码中设置SelectParameter?

时间:2017-02-07 15:13:37

标签: c# sql asp.net gridview sqldatasource

我一直收到错误,在尝试使用以下内容时必须声明标量变量“@inspIdFk”:

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
        { 
            ...
        }
    }

如何成功设置@inspIdFk的值?我验证了查询确实通过从WHERE子句中删除inspIdFk = @inspIdFk来提取数据。

1 个答案:

答案 0 :(得分:2)

据我了解,SqlDataSource.SelectParameters.Add采用参数名称而不是符号,因此您的添加应如下所示:

sdcRgActExps2.SelectParameters.Add("inspIdFk", inspidvalue);