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

后端 未结 3 458
一生所求
一生所求 2020-12-19 02:56

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 th

3条回答
  •  伪装坚强ぢ
    2020-12-19 03:13

    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.

提交回复
热议问题