Normally in ASP.Net TreeView you can enable it to show checkboxes in its node levels. So if you need to do any actions when a node is checked or unchecked you need to use the TreeNodeCheckChanged event. But the problem is TreeNodeCheckChanged event will not fire when a checkbox is clicked. The cause for this is because the TreeNode class which represents a node in the TreeView will not add onClick event on the checkbox.
But if you carefully check it the event is getting fired at the next page postback. Since I needed to do some actions when the checkbox statuses are changed I made the page post back when a checkbox is checked or unchecked by the following java script. What it does is simply it will check the element which caused the event is a checkbox and do a postback of the page.
- <script type="text/javascript">
- function TreeViewCheckBoxClicked(Check_Event) {
- var objElement;
- try {
- // Get the element which fired the event.
- objElement = window.event.srcElement;
- }
- catch (Error) {
- //srcElement is failing, objElement is null.
- }
- if (objElement != null) {
- // If the element is a checkbox do postback.
- if (objElement.tagName == "INPUT" && objElement.type == "checkbox") {
- __doPostBack("", "");
- }
- }
- else {
- // If the srcElement is failing due to browser incompatibility determine
- // whether the element is and HTML input element and do postback.
- if (Check_Event != null) {
- if (Check_Event.target.toString() == "[object HTMLInputElement]") {
- __doPostBack("", "");
- }
- }
- }
- }
- </script>
To make this work you need to bind the onClick event with the javascript shown above as shown below.
- protected void Page_Load(object sender, EventArgs e)
- {
- // Adding the onClick script to the TreeView.
- TreeView1.Attributes.Add("onClick", "TreeViewCheckBoxClicked(event)");
- }
Even though I have done this in Page Load this can be done in other places of code as well, for example if you are adding the TreeView by code you can use this right before adding it to the page.
The above will make the page post back when ever a checkbox in the TreeView is clicked, but nothing special will happen. You need to implement the code for TreeNodeCheckChanged event to get some task done out of it, for example I am using the following code to check or uncheck the child nodes depending on the action done for the parent node.
- protected void TreeView1_TreeNodeCheckChanged(object sender, TreeNodeEventArgs e)
- {
- // Loop through all the child nodes and change the checked status as required.
- foreach (TreeNode tn in e.Node.ChildNodes)
- {
- if (e.Node.Checked)
- tn.Checked = true;
- else
- tn.Checked = false;
- }
- }