TreeView’s TreeNodeCheckChanged and Firefox

Let’s create a TreeView control with checkboxes and a define a TreeNodeCheckChanged event:

<asp:TreeView runat="server" ID="TreeView1" ShowCheckBoxes="All" OnTreeNodeCheckChanged="TreeView1_TreeNodeCheckChanged"></asp:TreeVIew>

Unfortunately, this definition alone does not generate the required code that fires the TreeNodeCheckChanged event when a checkbox is changed. We need to manually fire this event with Javascript:

<script language="javascript" type="text/javascript">
	function onClientTreeNodeCheckChanged(e) {
		var o = e ? : window.event.srcElement;
		if (o.tagName == "INPUT" && o.type == "checkbox") {
			__doPostBack("", "");

Older versions of Internet Explorer define the window.event object (which also exists for newer versions of Internet Explorer and Chrome), however this object is undefined for other modern browsers such as Firefox. Modern web browsers (including newer versions of Internet Explorer) define instead. By checking whether e is defined, we can use for modern web browsers, including Firefox, otherwise we use window.event.srcElement for older versions of Internet Explorer.

Next, we need to bind the onClientTreeNodeCheckChanged javascript function to the TreeView control:

Private Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
	If Not IsPostBack Then
		TreeView1.Attributes.Add(HtmlTextWriterAttribute.Onclick.ToString(), "onClientTreeNodeCheckChanged(event)")
	End If
End Sub

Finally, add the TreeNodeCheckChanged event to your code behind file:

Private Sub TreeView1_TreeNodeCheckChanged(sender As Object, e As TreeNodeEventArgs)
	' Your code here
End Sub

And you’ve now got everything you need to run the TreeNodeCheckChanged event for both modern web browsers and older versions of Internet Explorer.


Thanks to:

Leave a Reply