4

我正在使用 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".

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

4

2 回答 2

10

添加参数时不需要,@例如:

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

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

于 2012-05-17T09:37:19.467 回答
1
<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
于 2012-05-17T09:36:30.500 回答