Search code examples
c#sqldatasource

Must declare the scalar variable "@LoggedInUser". Error when trying to add parameter to SqlDataSource


I am using SqlDataSource to show records based on the logged in user ,

<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>

And in the Page Load I am adding the parameter as follows

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

But it gives me error

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".

Can anybody point me out where I am going wrong. Thanks


Solution

  • You do not need the @ when adding the parameter eg:

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

    The @ symbol in the query indicates that the following text is the name of a parameter, however the @ is not considered part of the parameter name.