我正在使用Visual Basic .NET 2013,并且我想知道在树形视图中检查了哪些子节点。我不检查父节点,因为这些复选框仅在子节点中(我已禁用父节点中的复选框,因此它们不会出现)。
目前,我正在使用一种发现的解决方案:
Private Sub TreeView1_AfterCheck(sender As Object, e As TreeViewEventArgs) Handles TreeView1.AfterCheck
Dim childNodeCK As TreeNode = e.Node
If childNodeCK.Checked = True Then
If e.Node.Parent Is Nothing = False Then 'detects a Child Node
TextBox1.Text = TextBox1.Text & childNodeCK.Text
MessageBox.Show("Checked: " & childNodeCK.Text)
End If
End If
If childNodeCK.Checked = False Then
If e.Node.Parent Is Nothing = False Then
MessageBox.Show("Unchecked: " & childNodeCK.Text)
End If
End If
End Sub
但是我想知道是否还有另一种解决方案,像这样(以下代码没有显示任何内容,因为当我单击按钮来运行它时,什么也没有发生):
For Each childNode As System.Windows.Forms.TreeNode In TreeView1.Nodes
If childNode.Checked = True Then
MessageBox.Show(childNode.Text)
End If
Next
因为该想法是单击一个按钮并获得当时被检查的子节点的名称(文本)。因此,我认为我必须从头到尾逐一检查,如果子节点被选中,则执行一些代码。
答案 0 :(得分:0)
要获取所有选中的节点,您将必须使用递归函数或堆积列表。我更喜欢后者:
Private Function GetCheckedNodes() As List(Of TreeNode)
Dim result As New List(Of TreeNode)
'Get the root nodes
Dim nodes As New Stack(Of TreeNode)
For Each tn As TreeNode In TreeView1.Nodes
nodes.Push(tn)
Next
'Check each node and it's children
While nodes.Count > 0
Dim popNode As TreeNode = nodes.Pop
If popNode.Checked Then
result.Add(popNode)
End If
For Each tn As TreeNode In popNode.Nodes
nodes.Push(tn)
Next
End While
Return result
End Function
然后使用它:
For Each tn As TreeNode In GetCheckedNodes()
MessageBox.Show(tn.Text)
Next