Check / Uncheck All Child Nodes and Uncheck Parent Node in TreeView

As mentioned in my last post, I am working with a TreeView control that has been upgraded from VB6 to Visual Basic .NET (2012).  To programmatically cause the TreeNodes to be checked/unchecked properly, we must use the AfterCheck event.  Here is the code which is called from the AfterCheck event:

Public Sub CheckChildNodes(ByVal iNode As TreeNode)
Try
UnCheckParentNodes(iNode)
For Each sNode As TreeNode In iNode.Nodes
sNode.Checked = iNode.Checked
CheckChildNodes(sNode)
Next
Catch ex As Exception
End Try
End Sub

Public Sub UnCheckParentNodes(ByVal iNode As TreeNode)
Try
If iNode.Checked = False AndAlso iNode.Parent IsNot Nothing Then
iNode.Parent.Checked = False
UnCheckParentNodes(iNode.Parent)
End If
Catch ex As Exception
End Try
End Sub

And here is the code in the AfterCheck event that calls the above code:

Private Sub tvwDataCategory_AfterCheck(ByVal eventSender As System.Object, ByVal eventArgs As System.Windows.Forms.TreeViewEventArgs) Handles tvwDataCategory.AfterCheck
If eventArgs.Action = TreeViewAction.ByKeyboard Or eventArgs.Action = TreeViewAction.ByMouse Then
CheckChildNodes(eventArgs.Node)
End If
End Sub
Houston, TX 77002

One Reply to “Check / Uncheck All Child Nodes and Uncheck Parent Node in TreeView”

Leave a Reply