A.D. A.D. - 24 days ago 6
ASP.NET (C#) Question

<%= %> tag not working to display content inside an ASP Label control

Noob question.
Why does this not work into my .aspx file?

<asp:Label ID="Label1" runat="server" Text='<%=System.DateTime.Today.Day.ToString()%>' ></asp:Label>

It does display the <%=System.DateTime.Today.Day.ToString()%> string which is obviously not what I want.

Same result if I try to display the content of a code behind variable:

<asp:Label ID="label" runat="server" Text='<%= versionNumber %>' >

versionNumber being properly instanced and set into the code behind.


You cannot mix server controls with code blocks.

There are two ways to work around that limitation:

  • Just use <%=System.DateTime.Today.Day.ToString()%> without a Label around it
  • Use codebehind to set Label1.Text = System.DateTime.Today.Day.ToString();

The first way will display the date to the user, but you cannot further change it from codebehind. The second way does enable you to alter the text from codebehind.