none
treeview中,当某一级的节点中,当最后一个复选框被取消时,如何让它的父节点的复选框也自动取消 RRS feed

  • 问题

  • 在一个程序中,我需要这样,当同一级的节点的复选框一个一个都被选中时,当全被选中了,他的父节点也能自动选中,同时,当同一级节点的复选框一个一个被取消,当最后一个也被取消了,他的父节点复选框也能自动取消选中。代码如下,我已经实现了能自动选中或取消所选节点的所有子节点:

    Public Class frm_gzffb
        Private Sub TreeView1_AfterCheck(ByVal sender As Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles TreeView1.AfterCheck
            If e.Node.Checked = True Then
                GetTreeNode(e.Node.Nodes, "add")  '被选中时
            End If
            If e.Node.Checked = False Then
                GetTreeNode(e.Node.Nodes, "les")  '被取消时
            End If
        End Sub
        Private Sub GetTreeNode(ByVal nodes As TreeNodeCollection, ByVal ty As String)
            If ty = "add" Then
                For Each node As TreeNode In nodes
                    node.Checked = True
                    GetTreeNode(node.Nodes, ty)
                Next
            End If
            If ty = "les" Then
                For Each node As TreeNode In nodes
                    node.Checked = False
                    GetTreeNode(node.Nodes, ty)
                Next
            End If
        End Sub
    End Class

    2010年6月1日 7:29

答案

  • 这儿提供一个参考,有时会导致内存溢出。但是如果去掉GetTreeNode肯定没有问题。

    Public Class Form1

        Private Sub GetTreeNode(ByVal nodes As TreeNodeCollection, ByVal state As Boolean)
            For Each node As TreeNode In nodes
                node.Checked = state
                If (node.Nodes IsNot Nothing) Then
                    GetTreeNode(node.Nodes, state)
                End If

            Next
        End Sub


        Private Sub TreeView1_AfterCheck(ByVal sender As System.Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles TreeView1.AfterCheck
            If (e.Node.Parent IsNot Nothing) Then
                Dim count As Integer = 0

                For Each node In e.Node.Parent.Nodes
                    If (node.Checked) Then
                        count += 1
                    Else
                        count -= 1
                    End If
                Next

                If (Math.Abs(count) = e.Node.Parent.Nodes.Count) Then
                    e.Node.Parent.Checked = e.Node.Parent.Nodes(0).Checked
                End If
            End If

            'GetTreeNode(e.Node.Nodes, e.Node.Checked)  有时发生内存溢出,在此给出一个方案供大家参考改进,我们可以一起讨论


        End Sub
    End Class

    2010年6月1日 9:14
    版主