newdorp newdorp - 2 months ago 18
ASP.NET (C#) Question

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!

Answer

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)