13

I have a case that I need to set the Text property for an asp label in the aspx page not from code behind. More exactly, I need to set a value to asp control in aspx page and this value is set by a property in the same page code behind.

so I need to use an expression to do that like:

<asp:Label Text="<%= MyProperty %>" ..../>

I use:

<%= MyProperty %> doesn't work.
<%# MyProperty %> doesn't also.
Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
AshOoO
  • 1,108
  • 3
  • 13
  • 34

3 Answers3

29

Default.aspx.cs

public partial class _Default : System.Web.UI.Page
{
    public string CustomTitle = "This Is Title";

    protected void Page_Load(object sender, EventArgs e)
    {
        Page.DataBind();
    }
}

Default.aspx

<asp:Label Text='<%#CustomTitle %>' runat="server" />
Ricky Ruiz
  • 25,455
  • 6
  • 44
  • 53
archil
  • 39,013
  • 7
  • 65
  • 82
  • it's work but and it write the value on the page as html span but not work if I use it inside the label tag !! – AshOoO Apr 05 '11 at 08:29
14

You have to treat regular HTML and WebControls differently:


regular HTML:

Using <%= ... %> is sufficient:

<span><%= MyProperty %></span>

WebControls (stuff starting with <asp:...>):

<asp:Label Text='<%# MyProperty %>' />

In this case, you also have to call Me.DataBind() (VB) or this.DataBind(); (C#) in your codebehind, since <%# ... %> are data binding expressions.

Heinzi
  • 167,459
  • 57
  • 363
  • 519
  • I do call to this.DataBind in page load but dosen't work with me !!? – AshOoO Apr 05 '11 at 08:50
  • <%= ... %> doesn't work for me in a head section which has runat="server" set. The output source shows instead of . I have CSSVersionVal set as a Property in the codebehind and it's outputting correctly everywhere else in the page, but not in the head. – Craig Oct 08 '13 at 10:45
5
Page.DataBind();

Do you call this in your code? It binds all variables set in code to your page.

Headshota
  • 21,021
  • 11
  • 61
  • 82