3

Basically I would like to find a way to ddo something like:

<asp:Label ID="lID" runat="server" AssociatedControlID="txtId" Text="<%# MyProperty %>"></asp:Label>

I know I could set it from code behind (writing lId.Text = MyProperty), but I'd prefer doing it in the markup and I just can't seem to find the solution. (MyProperty is a string property) cheers

Adam Vigh
  • 1,260
  • 2
  • 13
  • 20

8 Answers8

11

You can do

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

And then a Page.DataBind() in the codebehind.

Mark S. Rasmussen
  • 34,696
  • 4
  • 39
  • 58
  • You left out the % on the left... should be: `Text='<%# MyProperty %>'` Regardless, thanks. You have the only answer which is 99% correct. :) Also worth noting, you can do this: `Text='<%# myClass.MyProperty %>'` – maplemale Aug 25 '14 at 00:44
10

Code expressions are an option as well. These can be used inside of quotes in ASP tags, unlike standard <%= %> tags.

The general syntax is:

<%$ resources: ResourceKey %>

There is a built-in expression for appSettings:

<%$ appSettings: AppSettingsKey %>

More info on this here: http://weblogs.asp.net/infinitiesloop/archive/2006/08/09/The-CodeExpressionBuilder.aspx

mrflippy
  • 126
  • 3
  • I do not think this is an answer for the question since the question specifically asks for the value of a property to be displayed in a label. I do not see how this method provides a way to achieve that. – Serhat Ozgel Sep 17 '08 at 10:30
  • using the CodeExpressionBuilder, I could easily display the value of the property on the label. Just check out that blog post, it's quite useful. – Adam Vigh Sep 19 '08 at 14:21
4

Leave the markup as is and make a call to Page.DataBind(); in your code behind.

John Sheehan
  • 77,456
  • 30
  • 160
  • 194
2
<asp:Label id="lID" runat="server"><%= MyProperty %></asp:Label>

since asp.net tags do not allow <% %> constructs, you cannot use Text="<%= MyProperty %>".

Serhat Ozgel
  • 23,496
  • 29
  • 102
  • 138
0

You can do this:

<asp:Label ID="lblCurrentTime" runat="server">
    Last update: <%=DateTime.Now.ToString()%>
</asp:Label>
A--C
  • 36,351
  • 10
  • 106
  • 92
Brian
  • 1
0

Call lID.Databind() from code-behind

Akselsson
  • 780
  • 4
  • 6
0
<div> <%=MyProperty"%></div>
DevelopingChris
  • 39,797
  • 30
  • 87
  • 118
  • Label control even does not render div tag. May be it would make sense if you suggested but even that would not have the same effect since you avoid all properties of a Label and disallowing the opportunity to use themes. – Serhat Ozgel Sep 16 '08 at 15:33
  • yeah, there's no need for a div in my case as I'm using the AssociatedControlId property of the control, to create a label for a textbox. – Adam Vigh Sep 16 '08 at 15:37
0

When you use <%# MyProperty %> declaration you need to databind it, but when using <%= MyProperty %> you don't (which is similar to just writing Response.Write(MyProperty).

Frederik Vig
  • 430
  • 1
  • 4
  • 11