ASP.NET 2.0 Treeview Checkboxes - Check All - Javascript

An update to this post is available at https://geekswithblogs.net/ranganh/archive/2009/01/21/updated-asp.net-treeview-checkboxes-ndash-check-all-ndash-javascript.aspx with suggestions from the comments below and it works when I last checked in IE 8 Beta2, Firefox 3.0.5 and Safari 3.2.1

ASP.NET 2.0 has introduced many new promising controls and TreeView is one among them. There has always been a requirement for Tree Control in earlier versions and it was quite hard to manage them with either the third party controls or the lighter version - IE Webcontrols.

Thanks to ASP.NET team, the 2.0 version rolled out with a built-in Treeview Control. The TreeView has many built-in features such as showing a checkbox for all the Tree Nodes. Node level formating, style, etc., Enabling the ShowCheckBoxes="All" property sets it to show a checkbox for all the nodes. The other options are Leaf, None, Parent and Root which show checkboxes at the respective node levels. None doesnt display CheckBoxes.

When we set ShowCheckBoxes="All", we would like to provide a feature where people can select the checkbox on the Root Node so that all the other checkboxes are checked automatically. Basically, when the parent node is checked, all the child nodes should be checked automatically.

It would be intuitive to accomplish this task at the client side without involving a postback.

The following code snippet helps in accomplishing the same.

TreeView Declaration

**<asp:TreeView ID="TreeView1" Runat="server" DataSourceID="XmlDataSource1" onclick="client_OnTreeNodeChecked();" ShowCheckBoxes="all">
**

<asp:TreeNodeBinding DataMember="Category" ValueField="ID" TextField="Name"></asp:TreeNodeBinding>

<asp:TreeNodeBinding DataMember="Description" ValueField="Value" TextField="Value"></asp:TreeNodeBinding>

**
**

</asp:TreeView>

In the above TreeView declaration Code, you can find the property onclick="client_OnTreeNodeChecked();" event which actually is the JavaScript function which would accomplish this task.

The Javascript Code snippet is as follows:-

_
You may find that in Visual Studio 2005 the onclick method declared in the TreeView is underlined as an error, but still it would work.

This is a simple but sometimes frustrating requirement and hope this benefits similar requirements.

Thanks to mtntime77 for posting the original idea.

A relevant article on XML Data binding with Treeview with checked state

Cheers and Happy TreeViewing.

This article is part of the GWB Archives. Original Author: Harish Ranganathan

New on Geeks with Blogs