Click here to Skip to main content
15,936,850 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi All.
I Am wondering how to detect if user doesn't chose the node on a tree view.
Because I get the Node name to do something like

dim id as string

id = TreeView1.SelectedNode.Name

it get error if user doesn't chose the node.

This function seem to have problem

Public Function NoNodeSelected(ByVal TView As TreeView)
    Dim nodes As TreeNodeCollection = TView.Nodes
    Dim n As TreeNode
    For Each n In nodes
        If n.IsSelected Then
            NoNodeSelected = False
        End If
    NoNodeSelected = True 'Không có node nào được chọn
    'Scroll through each Treeview Node

    'For i = 0 To TView.GetNodeCount(True) Step 1
    '    If TView.Nodes(i).IsSelected Then
    '        NoNodeSelected = False
    '    End If

    'For Each Node As TreeNode In TView.Nodes
    '    If Node.IsSelected Then
    '        NoNodeSelected = False
    '    End If
End Function

It only search the level 1.

Can anybody correct it?

1 solution

windows forms:
Use TreeView.SelectedNode[^] property, which get or set selected node for currently selected Treeview. If no TreeNode is currently selected, the SelectedNode property is a null reference (Nothing in Visual Basic).

To check it in code:
Dim tvn As System.Windows.Forms.TreeNode = Me.TreeView1.SelectedNode
MsgBox("Is selected node: " & (Not tvn Is Nothing).ToString)
Share this answer
phil.o 21-Mar-13 13:51pm    

No need to iterate through the complete collection, which can be huge with TreeViews.
Smart and concise. Thanks ;)
Maciej Los 21-Mar-13 14:22pm    
Thank you, phil.o ;)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900