Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I set the asp:Label Text property by calling a method in the aspx file?

Tags:

c#

asp.net

Can somebody please explain this to me:

I have a label and I want to be able to set the Text property by calling a method in the aspx file. It works fine if I set the property in code behind, but I really want to set this property in the aspx file.

I have tried a couple of things, but what I expected to work was this:

<asp:Label ID="Label1" runat="server" Text=<%# GetMyText("LabelText") %> />

I get no errors when doing this, but my method is never called and the Text property is left empty.

Is it not possible to set property values to server side controls directly in the aspx without using resources or use hard coded values?

Update: My first try was:

<asp:Label ID="Label1" runat="server" Text=<%= GetMyText("LabelText") %> />

But that results in the following error:

Server tags cannot contain <% ... %> constructs.

like image 701
GAT Avatar asked Oct 07 '09 06:10

GAT


People also ask

Which property show the text on control in asp net?

Remarks. Use the Text property to specify or determine the text content of the Label control. This property is commonly used to programmatically customize the text that is displayed in the Label control.

How do I right align a label in asp net?

When you add your label in the . aspx page, declare it with a CSS class or with style="text-align: right;". If you want to change the alignment during run-time, your best bet is to change the CssClass property of the Label.


1 Answers

The syntax =<%# ... %> is Data binding syntax used to bind values to control properties when the DataBind method is called.

You need to call DataBind - either Page.DataBind to bind all the controls on your page, or Label1.DataBind() to bind just the label. E.g. add the following to your Page_Load event handler:

    if (!IsPostBack)
    {
        this.DataBind();
        // ... or Label1.DataBind() if you only want to databind the label
    }

Using Text='<%= GetMyText("LabelText") %>' as others have proposed won't work as you'll find out. This syntax is inherited from classic ASP. It can be used in some circumstances in ASP.NET for inserting dynamic values in static HTML, but can not be used for setting propeties of server controls.

like image 83
Joe Avatar answered Oct 23 '22 19:10

Joe