0

I am trying to call a function defined in code behind from Label.Text but it's not working. Here is the code... code in .aspx file

<asp:Label runat="server" Text='<%# GetPagingCaptionString() %>' ID="pagenumberLabel"></asp:Label>

code block from code behind

public string GetPagingCaptionString()
        {
            int currentPageNumber = Convert.ToInt32(txtHidden.Value);
            int searchOrderIndex;
            if (int.TryParse(Convert.ToString(Session["searchOrderIndex"]), out searchOrderIndex))
            {
                return string.Format("{0} to {1} orders out of {2}", (currentPageNumber * 20) + 1,
                    (currentPageNumber + 1) + 20, GetItemsCount(searchOrderIndex.ToString()));
            }
            return String.Empty;
        }

Can anyone tell me what's wrong here.

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Abhash786
  • 881
  • 2
  • 24
  • 53

2 Answers2

3

Unless you're using a template based control (such as <asp:Repeater> or <asp:GridView>) then you can't use inline code-blocks such as you have within a server-side control.

In other words, you can't have <%=%> blocks within the attributes of server-side controls (such as <asp:Label>). The code will not be run and you will find the code is actually sent as part of the rendered HTML. The exception is for databinding controls where <%#%> code-blocks are allowed.

You're better off in this situation setting the .Text property in the code-behind itself.

For instance in your page-load function....

protected void Page_Load(object sender, EventArgs e)
{
  if (!Page.IsPostBack)
  {
    pagenumberLabel.Text = GetPagingCaptionString();
  }
}
freefaller
  • 19,368
  • 7
  • 57
  • 87
0

If you add a Property to your page it will be accessible from your aspx like so:

<asp:Label runat="server" Text='<%= PagingCaptionString %>' ID="pagenumberLabel" />

NB <%= %> tag rather than <%# %> which is used for databinding controls

Codebehind:

public string PagingCaptionString {
    get {
        int currentPageNumber = Convert.ToInt32(txtHidden.Value);
        int searchOrderIndex;
        if (int.TryParse(Convert.ToString(Session["searchOrderIndex"]), out searchOrderIndex))
        {
            return string.Format("{0} to {1} orders out of {2}", (currentPageNumber * 20) + 1,
                (currentPageNumber + 1) + 20, GetItemsCount(searchOrderIndex.ToString()));
        }
        return String.Empty;
    };
}
Chris L
  • 2,262
  • 1
  • 18
  • 33
  • I tried this but it is showing error like This is not scriptlet. This will be shown as plaintext. – Abhash786 May 18 '15 at 14:15
  • @Abhash786 - that is because you can't have `<%=%>` code-blocks within the attributes of server-side controls. See my answer – freefaller May 18 '15 at 14:15