How to apply styles to the TreeView node levels in ASP.NET

In practice applying styles based on the node level is more useful than applying styles to different types of nodes (described in the article: How to apply styles to the TreeView node types in ASP.NET).  That is because most trees use a strict hierarchy (for example, the first level of nodes represents categories, the second level represents products, the third represents orders, etc.).  In this case it is important to determine the node’s depth.

Because the TreeView control can have a theoretically unlimited number of node levels, it has a LevelStyles collection that can have as many entries you need for your project. The level is inferred from the position of the style in the collection, so the first entry is considered the root level, the second entry is the second node level, etc. For this system to work, you must follow the same order, and you must include an empty style placeholder if you want to skip a level without changing the formatting.

The next example shows a TreeView that doesn’t use any indenting but but instead differentiates levels by applying different amounts of spacing and different fonts:


<asp:TreeView runat=”server” HoverNodeStyle-Font-Underline=”true” ShowExpandCollapse=”false” NodeIndent=”0″>


<asp:TreeNodeStyle ChildNodesPadding=”12″ Font-Bold=”true” Font-Size=”11pt” ForeColor=”DarkGreen”/>

<asp:TreeNodeStyle ChildNodesPadding=”7″ Font-Bold=”true” Font-Size=”11pt” />

<asp:TreeNodeStyle ChildNodesPadding=”7″ Font-UnderLine=”true” Font-Size=”11pt” />