Common Function for Checking nodes of treeview?

rajesh.forum

Well-known member
Joined
Sep 7, 2007
Messages
55
Programming Experience
Beginner
Hi all!
i need Common function to check if there is existing nodes in treeview.
i cud nt write a function for this because the user will enter the node dynamically in my form.Please assume that there is 'n' no of node levels..
I ve used "for each" loop for each nodes and its childs..
Here is the sample code that i ve tried..

VB.NET:
Expand Collapse Copy
 For Each tNode As TreeNode In tvMenu.Nodes
                                If tNode.Text = tbMenuName.Text Then
                                    errMenu.ForeColor = Color.Red
                                    errMenu.Text = "Menu Name Already Exist"
                                Else
                                    For Each child As TreeNode In tNode.Nodes
                                        If child.Text = tbMenuName.Text Then
                                            errMenu.ForeColor = Color.Red
                                            errMenu.Text = "Menu Name Already Exist"
                                        End If
                                    Next
                                End If
Next




With regards
rajesh
 
Last edited by a moderator:
You can save yourself the trouble and set the Name of treenode equal to the Text when you create it. The Name property you see is used as key for the TreenodeCollection.Find method, and it has search recursive option.
VB.NET:
Expand Collapse Copy
If tvMenu.Nodes.Find(tbMenuName.Text, True) IsNot Nothing Then
    'node found
    'errMenu.ForeColor = Color.Red
    'errMenu.Text = "Menu Name Already Exist"
End If
If you wanted to learn how to write a recursive function like the Find method above then here is also an example of this:
VB.NET:
Expand Collapse Copy
Function NodeExists(ByVal nodes As TreeNodeCollection, ByVal text As String) As Boolean
    For Each node As TreeNode In nodes
        If node.Text = text Then Return True
        If NodeExists(node.Nodes, text) Then Return True '<---- see the function call itself, recursive !!
    Next
    Return False
End Function
called similar to above:
VB.NET:
Expand Collapse Copy
If NodeExists(tvMenu.Nodes, tbMenuName.Text) Then
    'node found
    'errMenu.ForeColor = Color.Red
    'errMenu.Text = "Menu Name Already Exist"
End If
Notice also that is not the job of this function to change your UI elements, its only job is to search and return result. It's OOP good practise. When you get the result you decide what to do with it, this means many people can use this function for different purposes.
 
Back
Top