0

I have a label and I want to set text of this label to

HTTPContext.Current.User.Identity.Name

So I wrote

Text = '<%=HTTPContext.Current.User.Identity.Name %>'

but it doesn't work, however when I wrote this outside of the lable for example:

<h2>
<%=HTTPContext.Current.User.Identity.Name %>
</h2>

it works.

Brian Mains
  • 50,520
  • 35
  • 148
  • 257
HOY
  • 1,067
  • 10
  • 42
  • 85

3 Answers3

4
<asp:Label ID="lbUserName" 
           runat="server"
           Text='<%# HttpContext.Current.User.Identity.Name %>'
            />

in Page_Load

if (!Page.IsPostBack )
{
   lbUserName.DataBind();
}
Adrian Iftode
  • 15,465
  • 4
  • 48
  • 73
  • Still displays null (Edit: my mistake) – HOY Mar 20 '12 at 12:39
  • @HOY you should check your HttpContext.Current.User.Identity.Name is not null. the above solution should work – Devjosh Mar 20 '12 at 12:42
  • But what about the same issue in the problem? The databinding is not working in here http://stackoverflow.com/questions/9863899/passing-windows-user-id-as-parameter-to-sqldatasource-gives-databinding-exceptio – HOY Mar 26 '12 at 07:42
1

use label like this

<asp:label id="lblx" runat="server" ><%= HTTPContext.Current.User.Identity.Name %></asp:label>
Özgür Kara
  • 1,333
  • 10
  • 22
1

To bind the text like this you will have to create your own custom expression builder.

First, add such class to your namespace:

using System.Web.Compilation;
using System.CodeDom;

[ExpressionPrefix("Code")]
public class CodeExpressionBuilder : ExpressionBuilder
{
    public override CodeExpression GetCodeExpression(BoundPropertyEntry entry,
        object parsedData, ExpressionBuilderContext context)
    {
        return new CodeSnippetExpression(entry.Expression);
    }
}

Next step is adding this to your web.config file:

<compilation debug="true">
    <expressionBuilders>
        <add expressionPrefix="Code" type="YourNameSpace.CodeExpressionBuilder"/>
    </expressionBuilders>
</compilation>

Then finally this should work:

<asp:Label id="YourLabel" runat="server" Text='<%$ Code:HttpContext.Current.User.Identity.Name %>' />

Complicated way to achieve something simple, but this will allow you to use the syntax you want throught your whole project so might worth the extra effort.

Reference.

Shadow The GPT Wizard
  • 66,030
  • 26
  • 140
  • 208