How to use User.Identity.Name as a parameter for SqlDataSource in ASP.NET?

两盒软妹~` 提交于 2019-11-30 18:34:25
Jan Jongboom

Declare it in your .aspx and fill it in your codebehind:

aspx

<asp:Parameter Name="username" Type="String" DefaultValue="Anonymous" />

codebehind

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

You can also accomplish this by creating a hidden textbox on the page, apply the User.Identity.Name to the value and then use the formcontrol parameter in the SQL data source. The advantage here is that you can reuse the code in the select, insert, delete, and update parameters without extra code.

So in aspx we have (noneDisplay is a css class to hide it):

<asp:TextBox runat="server" ID="txtWebAuthUser" CssClass="noneDisplay"></asp:TextBox>

and in the Update parameter of the sql datasource update section:

<asp:ControlParameter Name="CUrrentUser"  ControlID="txtWebAuthUser" Type="String" PropertyName="Text" />

which gets interpreted in the update something like this:

UpdateCommand="UPDATE [Checks] SET [ScholarshipName] = @ScholarshipName, [Amount] = @Amount,LastModifiedBy=@CUrrentUser,
         [LastModified] = getdate() WHERE [CheckId] = @CheckId"

and then in the .cs file form load we have:

this.txtWebAuthUser.Text = User.Identity.Name; 

This technique has worked well in many places in all of our applications.

in asp page put a blank datasource with a connectionstring

e.g.

<asp:SqlDataSource ID="SqlDataSourceDeviceID" runat="server" ConnectionString="<%$ ConnectionStrings:myConnectionString %>">
<asp:DropDownList ID="DropDownListDeviceID" runat="server" DataSourceID="SqlDataSourceDeviceID" DataTextField="DevLoc" DataValueField="DeviceId"></asp:DropDownList>

in code behind on pageload

  protected void Page_Load(object sender, EventArgs e)
    {
if (!IsPostBack) {
   String myQuery =String.Format("SELECT DeviceID,DevLoc  FROM  ... where UserName='{0}')",User.Identity.Name);
   SqlDataSourceDeviceID.SelectCommand = myQuery;
   SqlDataSourceDeviceID.DataBind();
   DropDownListDeviceID.DataBind();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!