Search code examples
asp.nettreeviewcode-behind

How to display server side variable inside a TreeNode's Text Attribute?


.cs file:

public partial class Default2 : System.Web.UI.Page
{
    public string s;
    protected void Page_Load(object sender, EventArgs e)
    {
        s = "Director";
    }
}

.aspx file:

<asp:TreeView ID="TreeView1" runat="server">
      <Nodes>
           <asp:TreeNode Text="<%=s %>"></asp:TreeNode>
      </Nodes>
</asp:TreeView>

this outputs <%=s%> instead of the value of s.


Solution

  • You actually can't use those types of expressions in server tag attributes, per, "Introduction to ASP.NET inline expressions in the .NET Framework" (MSDN), under the "<%= ... %> displaying expression" heading:

    Remember that the displaying expression cannot be used in the attributes of server controls. This is because the .NET Framework directly compiles the whole expression instead of the displaying content as the value to the attribute.

    If you do want to set the value of that node, in your example, you'd have to set it like this:

    public string s;
    protected void Page_Load(object sender, EventArgs e)
    {
        s = "Director";
        TreeView1.Nodes[0].Text = s;
    }