简体   繁体   中英

Pass parameter value to SqlDataSource ASP.NET User.Identity.Name

Need help! I can't get around why this doesn't work.

Page:

<asp:SqlDataSource ID="SelectUserInfo" runat="server" ConnectionString="<%$ ConnectionStrings:TradeRelay %>" SelectCommand="admin_userinfo" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:ControlParameter Name="suser" Type="String" DefaultValue="Anonymous" />
</SelectParameters>
</asp:SqlDataSource>

CodeBehind:

protected void Page_Init(object sender, EventArgs e)
{
    SelectUserInfo.SelectParameters["suser"].DefaultValue = User.Identity.Name;
}

Error:

Could not find control 'suserParam' in ControlParameter 'suser'

UPD:

ControlID="suserParam"

was wrong! Thanks!

I suggest to add Hiddenfield control and assign the User.Identity.Name to it then make the SelectUserInfo get the parameter value from the Hiddenfield control

by the way, in your code i didn't find any control with the name suserParam

<asp:HiddenField runat="server" ID="suserParam"/>
<asp:SqlDataSource ID="SelectUserInfo" runat="server" ConnectionString="<%$ ConnectionStrings:TradeRelay %>" SelectCommand="admin_userinfo" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:ControlParameter ControlID="suserParam" Name="suser" Type="String" DefaultValue="Anonymous" />
</SelectParameters>
</asp:SqlDataSource>

this is the code behind

protected void Page_Load(object sender, EventArgs e)
{
    suserParam.value = User.Identity.Name;
}

Your are using ControlParameter which extracts the parameter value from the control existing on the page. So in this case, it is trying to find control with id suserParam and raising error as it is unable to find it.

Try using plain parameter ( asp:Parameter ) instead of ControlParameter. Yet another alternative is using SessionParameter or writing your own custom parameter (see this SO question: How to utilize ASP.NET current user name in SqlParameter without code-behind )

您可以将其直接包含为标准参数:

<asp:Parameter Name="suserParam" Type="String" DefaultValue="<%=User.Identity.Name %>" />

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