Introduction
Recently I was faced with a requirement to provide automatic numbering for an ASP.NET
TreeView
and I did it using CSS counters. I am providing here the
CSS I used and the TreeView
markup
so that someone else might find it useful.
Using the Code
Here is the HTML markup for the ASP.NET TreeView
control I am using. Please take note of the CSS class LinksTreeView
I used for the TreeView
and the CSS
class TreeItem
used for the nodes (NodeStyle
).
<asp:TreeView ID="LinksTreeView" Font-Names="Arial" Font-Size="12px" ForeColor="Black"
runat="server" CssClass="LinksTreeView">
<SelectedNodeStyle BackColor="#6699FF" ForeColor="White" />
<NodeStyle CssClass="TreeItem" />
</asp:TreeView>
The TreeView control gets rendered inside a container div
with the class we specify. For each node of the TreeView
, there is a table added to the
HTML.
I am creating CSS counters for tables inside the container div and using the HTML pseudo element ':before
' with the anchor tag that gets
created for each node to display the section numbering in place.
<style type="text/css">
div.LinksTreeView table:first-child
{
counter-reset: treecount;
}
div.LinksTreeView table
{
counter-increment: treecount;
}
div.LinksTreeView td.TreeItem > a:before
{
content: counters(treecount, ".") ". ";
font-weight: bold;
}
</style>
When used inside an UpdatePanel
there is an IE bug that causes all the numbering to
be reset to 0 on postbacks. There are a few workarounds involving an empty div
and inserting a space into it. But I wasn't able to solve the issue entirely and
I had to remove the UpdatePanel
to fix this problem on IE.
Points of Interest
It was the first time I came across CSS counters and the ease with which I could add numbering to
a TreeView
really made me write this tip.
Previously I was modifying Node.Text
to include numbering which proved
to be a pain as I also had to implement TreeView
editing (both structure and data).
History
No changes yet.