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.
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();
}
}
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;
};
}