【问题标题】:Must declare the scalar variable "@LoggedInUser". Error when trying to add parameter to SqlDataSource必须声明标量变量“@LoggedInUser”。尝试向 SqlDataSource 添加参数时出错
【发布时间】:2012-05-17 09:32:24
【问题描述】:

我正在使用 SqlDataSource 根据登录用户显示记录,

<asp:SqlDataSource ID="ModifyCustomerDataSource" SelectCommand="SELECT cApplicationNo,cFirstName,cMiddleName,cLastName,nTelNo,nMobileNo,cPanGirNo from Data_Customer_Log where cAddedBy=@LoggedInUser" ConnectionString="<%$ ConnectionStrings:CwizDataConnectionString %>"   runat="server"></asp:SqlDataSource>

在页面加载中我添加如下参数

protected void Page_Load(object sender, EventArgs e)
        {
            string user = HttpContext.Current.User.Identity.Name;
            ModifyCustomerDataSource.SelectParameters.Clear();
            ModifyCustomerDataSource.SelectParameters.Add("@LoggedInUser", user.Trim());
        }

但它给了我错误

Must declare the scalar variable "@LoggedInUser".
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.Data.SqlClient.SqlException: Must declare the scalar variable "@LoggedInUser".

谁能指出我哪里出错了。 谢谢

【问题讨论】:

  • 这是使用 sqldatasource 的最佳实践吗?只是好奇。我在不使用 sqldatasource 的情况下工作。如果你想要示例代码,请告诉我..
  • @AnandMohanAwasthi,我正在将此数据绑定到我的 jqGrid,所以这对我来说是更简单的方法,但不知道它是否是最佳实践,你能问一下富有的 okelly 吗?示例代码会帮助我。谢谢

标签: c# sqldatasource


【解决方案1】:

添加参数时不需要@ eg:

ModifyCustomerDataSource.SelectParameters.Add("LoggedInUser", user.Trim());

查询中的@ 符号表示以下文本是参数名称,但@ 不被视为参数名称的一部分。

【讨论】:

  • 今晚有太多时间和太多难听的话。
【解决方案2】:
<asp:SqlDataSource ID="ModifyCustomerDataSource" SelectCommand="SELECT cApplicationNo,cFirstName,cMiddleName,cLastName,nTelNo,nMobileNo,cPanGirNo from Data_Customer_Log where cAddedBy=@LoggedInUser" ConnectionString="<%$ ConnectionStrings:CwizDataConnectionString %>"   runat="server">

        <SelectParameters>

            <asp:Parameter Name="LoggedInUser" />

        </SelectParameters>

</asp:SqlDataSource>

验证您是否在 Sqldatasource 中定义了 SelectParameter 作为上述示例。

可以通过两种方式设置参数的值:

ModifyCustomerDataSource.SelectParameters["LoggedInUser"].DefaultValue = "some value";

or

ModifyCustomerDataSource.SelectParameters.Add("@LoggedInUser", user.Trim()); //@is must here with the parameter name

【讨论】:

  • 问题解决了,富豪的回答有帮助。谢谢你的回答。
  • ModifyCustomerDataSource.SelectParameters.Add("@LoggedInUser", user.Trim()); ,不工作,删除 @ 为我工作
  • 它起作用了,因为根据我的示例,您没有在 aspx 中提到“LoggedInUser”的 标签。
猜你喜欢
  • 2013-06-26
  • 1970-01-01
  • 2017-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-21
  • 1970-01-01
相关资源
最近更新 更多