Sunteți pe pagina 1din 12

Figure 4: Creating a Node with Specific Properties.

The Solution The application solution contains a single Windows Application project comprised ; all code supplied in support of this project is contained in two form classes; one is the main form containing the TreeView and a few controls used to display node information (Figures 1, 2, and 3) and to execute searches for a specific n ode or group of nodes based upon a user supplied search term. The other form cla ss (Figure 4) is used to create new nodes; within the application, this form is displayed by selecting a node from the TreeView and then selecting the "Add Node " option from the context menu. There is nothing custom or fancy done with any of the TreeView related component s in this application; it is merely a demonstration of how to work with a TreeVi ew within the context of a Windows Forms application. The Code: Form 1 - The Main Form The main form class is a standard window form with a few controls added; the for m contains a split container control; on the left hand side of the control is a TreeView controls, on the right hand side of the splitter are four group boxes; the first group box contains a set of labels and text boxes used to display info rmation about a selected node, the remaining group boxes contain labels, text bo xes, and buttons used to conduct different searches of the TreeView's node colle ction based on the node's text, name, or tag values. The functionality contained in the class is broken up into several regions; the class begins with the default class declaration: Public Class Form1

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

' start off by adding a base treeview node Dim mainNode As New TreeNode() mainNode.Name = "mainNode" mainNode.Text = "Main" Me.treeView1.Nodes.Add(mainNode)

End Sub

The form class constructor creates a main node in the TreeView control; at runti me, the user may select this node (or any child node originating form this node)

to add additional nodes to the TreeView. The form class also contains a context menu; this context menu contains two options; one to add a new node, and one to delete an existing node. When a new node is requested, the application opens an instance of the New Node dialog; this dialog forces the user to set the name, t ext, and tag values for the new node. The tag value can be any object but in thi s example, the tag is limited to holding an additional string value. Once the va lues have been collected from the dialog, the new node is populated with the inf ormation and added to the selected node of the TreeView.

When a node is deleted, the selected node and all of its children are removed fr om the TreeView; one thing to note here is, if you are associating an object wit h a node through its tag; you will want to write the handler to destroy that obj ect prior to deleting the selected node.

#Region "Add and Remove Nodes"

Private Sub cmnuAddNode_Click(ByVal sender As System.Object, ByVal e As System.E ventArgs) Handles cmnuAddNode.Click

Dim n As New Form2() n.ShowDialog() Dim nod As New TreeNode() nod.Name = n.NewNodeName.ToString() nod.Text = n.NewNodeText.ToString() nod.Tag = n.NewNodeTag.ToString() n.Close()

treeView1.SelectedNode.Nodes.Add(nod) treeView1.SelectedNode.ExpandAll()

End Sub

Private Sub cmnuRemoveNode_Click(ByVal sender As System.Object, ByVal e As Syste m.EventArgs) Handles cmnuRemoveNode.Click

treeView1.SelectedNode.Remove()

End Sub

#End Region

The next region of code is used to handle TreeView events; there are only two ev ents handled in this section; the TreeView's After Select event and the TreeView 's click event. The After Select event handler is used to populate the text boxe s used to display information from the selected node (its Name, Text, Tag, and P arent text properties. The find functions described later highlight all found no des in response to a search by setting the background color of each matching nod e to Yellow; the click event handler for the TreeView is used to remove all such highlighting.

#Region "Treeview Event Handlers"

Private Sub treeView1_AfterSelect(ByVal sender As System.Object, ByVal e As Syst em.Windows.Forms.TreeViewEventArgs) Handles treeView1.AfterSelect

Try txtName.Text = "" txtParentName.Text = "" txtText.Text = "" txtTag.Text = ""

txtName.Text = treeView1.SelectedNode.Name.ToString() txtText.Text = treeView1.SelectedNode.Text.ToString() txtTag.Text = treeView1.SelectedNode.Tag.ToString() txtParentName.Text = treeView1.SelectedNode.Parent.Text.ToString() Catch 'do nothing End Try

End Sub

Private Sub treeView1_Click(ByVal sender As System.Object, ByVal e As System.Eve ntArgs) Handles treeView1.Click

ClearBackColor()

End Sub

#End Region

The next region in the class is used to find a node by its name property. The me thod of finding a node by its name is the only find function directly supported by the TreeView; if you want to find a node by something other than its name, yo u will have to write your own methods to do so. This click event handler populat es an array of nodes with an array of nodes with matching names. The find method accepts to arguments; the first argument is the search term and the second is a Boolean value used to determine whether or not child nodes should also be inclu ded in the search; in this case the search term is collected from a text box on the form and the option of searching child nodes is enabled by setting the secon d argument to true.

Once the collection of nodes is created; each matching node has its back color s et to yellow so as to highlight the node in the TreeView. Prior to setting the b ack color of the matching nodes, all of the other nodes in the TreeView are set back to having white backgrounds by calling the Clear Back Color method.

#Region "Find Node By Name"

Private Sub btnFindNode_Click(ByVal sender As System.Object, ByVal e As System.E ventArgs) Handles btnFindNode.Click

ClearBackColor() Try Dim tn() As TreeNode = treeView1.Nodes(0).Nodes.Find(txtNodeSearch.Text, True) Dim i As Integer = 0

For i = 0 To tn.Length treeView1.SelectedNode = tn(i) treeView1.SelectedNode.BackColor = Color.Yellow Next i

Catch 'do nothing End Try

End Sub

#End Region

The next region of code is used to remove the back color from any nodes highligh ting in an earlier search. This process relies on two separate methods. The firs t method creates an instance of a tree node collection containing all of the nod es in the form's TreeView control. Each of the nodes in the collection is passed to a second method (Clear Recursive); this second method is passed the current node. The Clear Recursive method loops through all of the nodes contained within the passed in nodes node collection and sets the back color of each of those no des to the color white. Each node is then passed recursively back to the same Cl ear Recursive method where each node's node collection is processed until there are not more nodes remaining to process. In this way, each node and child node i n the entire tree is processed.

While this process is used merely to set each node's back color to white, the sa me approach may be used whenever the entire tree must be processed; in fact, the remaining search methods will do just that.

#Region "Remove BackColor"

'recursively move through the treeview nodes 'and reset backcolors to white Private Sub ClearBackColor()

Dim nodes As TreeNodeCollection nodes = treeView1.Nodes Dim n As TreeNode

For Each n In nodes ClearRecursive(n) Next

End Sub

'called by ClearBackColor function Private Sub ClearRecursive(ByVal treeNode As TreeNode)

Dim tn As TreeNode

For Each tn In treeNode.Nodes tn.BackColor = Color.White ClearRecursive(tn) Next

End Sub

#End Region

The next region of code is used to find a node or nodes with text properties mat ching a search expression. The form contains a group box used to set a text sear ch term and envoke the method from a button click event handler. The button clic k first clears all highlighted nodes by calling the Clear Back Color method; aft er the nodes are all restored to white backgrounds, the handler calls the Find b y Text method; this method works much like the method described for clearing the back color. The method assembles a collection of the tree view nodes and then p asses each node to the recursive method. The find recursive method looks for nod es with text properties matching the search expression and, when a match is foun d, sets the back color to yellow. Each processed node is passed back to the fin d recursive method which will continue to examine each node until all of the nod es in the tree have been evaluated.

#Region "Find By Text"

Private Sub btnNodeTextSearch_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNodeTextSearch.Click

ClearBackColor() FindByText()

End Sub

Private Sub FindByText() Dim nodes As TreeNodeCollection = treeView1.Nodes Dim n As TreeNode For Each n In nodes FindRecursive(n) Next End Sub

Private Sub FindRecursive(ByVal tNode As TreeNode)

Dim tn As TreeNode For Each tn In tNode.Nodes ' if the text properties match, color the item If tn.Text = Me.txtNodeTextSearch.Text Then tn.BackColor = Color.Yellow End If

FindRecursive(tn)

Next

End Sub

#End Region

The next region is used to contain the methods used to find nodes by their tag v alue (which in this case is a string); and to highlight in yellow any matching n odes. These methods work much like the last method with the exception that the m atches are determined by their tag values rather than their text values.

#Region "Find By Tag"

Private Sub btnNodeTagSearch_Click(ByVal sender As System.Object, ByVal e As Sys tem.EventArgs) Handles btnNodeTagSearch.Click

ClearBackColor() FindByTag()

End Sub

Private Sub FindByTag() Dim nodes As TreeNodeCollection = treeView1.Nodes Dim n As TreeNode For Each n In nodes FindRecursiveTag(n) Next End Sub

Private Sub FindRecursiveTag(ByVal tNode As TreeNode)

Dim tn As TreeNode

For Each tn In tNode.Nodes ' if the text properties match, color the item If tn.Tag.ToString() = Me.txtTagSearch.Text Then tn.BackColor = Color.Yellow End If

FindRecursiveTag(tn) Next

End Sub

#End Region

End Class

That wraps up all of the code necessary to add and remove nodes, and to search f or specific nodes based upon their name, text, or tag values. The Code: Form 2 - New Node Form The code supplied in the New Node form is used merely to capture the user suppli ed values used to populate a newly created node's name, text, and tag properties . The form is displayed as a dialog and appears in response to the user requesti ng the addition of a new node from the main form of the application. The class d eclaration is in the default configuration for a form class: Public Class Form2

Following the class declaration, three local member variables are defined; each of which is used to store the user supplied name, text, and tag properties:

Private mNewNodeName As String Private mNewNodeText As String Private mNewNodeTag As String

The next region of code is used to define three public properties used to hold t he new node name, text, and tag values. Once the user has set these values on t

his form, the main form collects these properties and assigns them to the new no de's name, text, and tag properties.

#Region "Class Properties"

Public Property NewNodeName() As String Get Return mNewNodeName End Get Set(ByVal value As String) mNewNodeName = value End Set End Property

Public Property NewNodeText() As String Get Return mNewNodeText End Get Set(ByVal value As String) mNewNodeText = value End Set End Property

Public Property NewNodeTag() As String Get Return mNewNodeTag End Get Set(ByVal value As String) mNewNodeTag = value End Set End Property

#End Region

This button click event handler is intended to force the user to set all three v alues; once each is set, the related properties are passed the correct values an d the form is closed.

Private Sub btnSubmit_Click(ByVal sender As System.Object, ByVal e As System.Eve ntArgs) Handles btnSubmit.Click

If txtNewNodeName.Text <> String.Empty Then NewNodeName = txtNewNodeName.Text Else MessageBox.Show("Name the node.") Return End If

If txtNewNodeText.Text <> String.Empty Then NewNodeText = txtNewNodeText.Text Else MessageBox.Show("Provide the new node's text") Return End If

If txtTag.Text <> String.Empty Then NewNodeTag = txtTag.Text Else MessageBox.Show("Provide the new node's text") Return End If

Me.Close()

End Sub

End Class That is all there is to it. Once this code is executed, may right click on the m ain node and add as many nodes and child nodes as they see fit. The user may ent er in valid search expression into any of the search optons and highlight matchi ng nodes, or the user may select nodes from the tree and read the associated nam e, text, tag and parent values from the selected node. Summary

S-ar putea să vă placă și