简体   繁体   中英

SQLDataSourceParameter parameter for query not working when hard coding a string does

I have a drop down menu. My goal is to make it where the currently logged in person is first on the list, followed by an alphabetical list:

<asp:DropDownList ID="userNameDropDown" runat="server" DataSourceID="SqlDataSource1"
    DataTextField="Name" DataValueField="PK_User" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged" AutoPostBack="true">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ApplicationServices %>"
    SelectCommand="SELECT [PK_User], [Name] FROM [User] ORDER BY CASE WHEN [LoginName] = '@userLoggedIn' THEN 1 ELSE 2 END, [Name]">
<SelectParameters>
    <asp:QueryStringParameter Name="userLoggedIn" Type="String" />
</SelectParameters>
</asp:SqlDataSource>

Here is my C# that should set the parameter:

protected void Page_Load(object sender, EventArgs e)
{
    SqlDataSource1.SelectParameters["userLoggedIn"].DefaultValue = User.Identity.Name;
}

The result is that the list is shown in alphabetical order, ignoring the logged in person. If I change the SelectCommand and make it hardcoded it works fine:

SelectCommand="SELECT [PK_User], [Name] FROM [User] ORDER BY CASE WHEN [LoginName] = 'tunnelld' THEN 1 ELSE 2 END, [Name]

In this case it does exactly what I want.

System.Diagnostics.Debug.Write(User.Identity.Name);

results in the output of : tunnelld

I figured out the problem:

[LoginName] = '@userLoggedIn'

should not have quotes, the following fixes it:

[LoginName] = @userLoggedIn

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM