1

I'm trying to write my codebehind property FirstName to Text property of Label. But I don't want to do it from code behind. This is my example:

<asp:Label ID="Label1" runat="server" Text='<%# "Hello " + this.FirstName %>'></asp:Label>

But it doesn't show anything. How can I correct it?

Earlgray
  • 647
  • 1
  • 8
  • 31

1 Answers1

0

I am not sure why you are trying to do that, but you can do it by calling the DataBind method of control like this:-

public string FirstName { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
    FirstName = "XYZ";
    if (!IsPostBack)
          Label1.DataBind();
}

Update:

Data Bind code nuggets <%# will work only with DataBound Controls. To make them work with normal ASP.NET controls, you will have to explicitly call the DataBind method of that control like I did above.

Text='<%# "Hello " + this.FirstName %>'

Will print Hello XYZ here. You can also check this answer for further explanation.

Community
  • 1
  • 1
Rahul Singh
  • 21,585
  • 6
  • 41
  • 56
  • 3
    He don't want to use codebehind. Also, if you would use it it would be simply `Label1.Text = "Hallo " + this.FirstName;` – Tim Schmelter Nov 20 '15 at 08:29
  • @TimSchmelter - Yeah agree, OP doesn't want to use code behind but for this to work (code nugget) `DataBind` method has to be invoked. And it will work I guess you tried it with `<%=` try it with data bind code nugget `<%#` and it will work just fine. – Rahul Singh Nov 20 '15 at 08:32
  • @TimSchmelter - That's what I mentioned in the update, you can't use the property directly with code nuggets like this - `<%=` it will not work. – Rahul Singh Nov 20 '15 at 08:37