how to Check All and Uncheck All in TreeView1 By Click on Button1 in vb.net?

Shahab a 261 Reputation points
2022-09-09T14:23:16.053+00:00

Hi all
how to Check All and Uncheck All in TreeView1 By Click on Button1 in vb.net?
See This Pic and help me
thanks all
239545-1.png

Developer technologies | VB
0 comments No comments
{count} votes

Accepted answer
  1. Michael Taylor 60,326 Reputation points
    2022-09-09T15:03:39.827+00:00

    Unfortunately there is no easy way to do that other than to manually enumerate the children. The easiest approach is to listen for the AfterCheck event on the treeview. When it fires then enumerate the child nodes using Nodes property and check/uncheck each child. Since you've hooked the event that would recursively call the handler for each child.

       Public Class Form1  
           Private Sub OnAfterCheck(sender As Object, e As TreeViewEventArgs) Handles TreeView1.AfterCheck  
               For Each child As TreeNode In e.Node.Nodes  
                   child.Checked = e.Node.Checked  
               Next  
           End Sub  
       End Class  
    

    If you wanted to make this reusable then you could wrap this logic into a derived TreeView class.

    Note that this might not perform well if the treeview is large and it doesn't handle virtual items.

    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Dewayne Basnett 1,381 Reputation points
    2022-09-15T15:53:37.367+00:00

    Give this a try,

        Private Sub btnCheckAll_Click(sender As Object, e As EventArgs) Handles btnCheckAll.Click  
            SetCheckState(TreeView1, True)  
        End Sub  
      
        Private Sub btnUn_Click(sender As Object, e As EventArgs) Handles btnUn.Click  
            SetCheckState(TreeView1, False)  
        End Sub  
      
        Private Sub SetCheckState(tv As TreeView, checkState As Boolean)  
            SetNode(tv.Nodes(0), checkState)  
        End Sub  
      
        Private Sub SetNode(Node As TreeNode, checkState As Boolean)  
            Node.Checked = checkState  
            ' Node.EnsureVisible() ' for debug  
            For Each nd As TreeNode In Node.Nodes  
                SetNode(nd, checkState)  
            Next  
        End Sub  
      
    
    1 person found this answer helpful.
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.