at-hex
at-hex

Reputation: 3130

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!

Upvotes: 1

Views: 8470

Answers (3)

M Bowen
M Bowen

Reputation: 30

You can include it directly as a standard Parameter:

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

Upvotes: -1

Nour Berro
Nour Berro

Reputation: 560

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

Upvotes: 2

VinayC
VinayC

Reputation: 49195

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)

Upvotes: 2

Related Questions