Project: Using Treeview: Download The Code Here
Project: Using Treeview: Download The Code Here
We are going to assign the tree Figure above into TreeView and sort the value. This tree has keys
(inside the circles), Description, and Value. Before we make the program, we prepare this tree
into an array (as in table below). The array consists of four rows. The first row is the parent key
of the node. The second row represents the key of the node, the third row corresponds to the
values of the node and the last row characterized the description of each node. Each column
denotes each node of the tree.
Parent Key - R R C1 C1 C1 C2 C2
Node Key R C1 C2 C11 C12 C13 C21 C22
Node
14.2 15.1 12.3 16.3 11.4 19.9 46.2 12.7
Value
Node
Root Child1 Child2 Grandchild1 Grandchild2 Grandchild3 Grandchild4 Grandchild5
Description
By default, the TreeView will sort only string. To sort number correctly, they must the same
digits (e.g. 11.2 and 12.45 have different digit). Thus we need to format the number before
sorting it. After we sort the number, we add the description text.
End Sub
There are many other data structures that you can learn by yourself. Let this short introduction
encourage you to learn more about the fun of programming.
Para trabajar con este control, primero es necesario añadir el componente en la barra de
herramientas. Para ello vamos al cuadro de dialogo Componentes y marcamos el control
Microsoft Windows Common Controls 6.0 Apareceran varios controles y entre ellos el que nos
interesa: TreeView.
Lo que se va a hacer en este ejemplo va a ser cargar el control de forma manual sin utilizar
ningun origen de datos. El resultado final será como el de la imagen...
Este es el codigo para empezar a cargar de forma manual cada nodo del arbol y sus ramas. Al
objeto TreeView le hemos llamada arbol. Despues, debe crearse una variable de tipo Node a la
que se va a añadir con el metodo Add cada nodo. La sintaxis de este metodo es:
El primer nodo padre sera CLIENTES, y sus sucesivos hijos desde Amigos1 hasta Amigos8. Una
vez cargado el nodo padre pasamos a cargar los nodos hijos. El esquema a seguir es el siguiente:
para hacer referencia al nodo padre utilizamos como nodo-referencia el nombre "Raiz". Despues
indicamos como parametro a PosRelativa con el valor tvwChild. Para el parametro clave hemos
utilizado en este caso "clave1" hasta "clave8". Para el texto, como ultimo parametro cualquier
nombre.
End Sub
Para hacer referencia a cada nodo cuando se haga click sobre uno de ellos, se utiliza el evento
objeto_NodeClick(ByVal Node As MSComctlLib.Node)
End Sub
Utilizamos tres propiedades: Parent, Key y Text. Parent se refiere al nodo padre, Key al
parametro clave y la propiedad Text visualiza el texto del nodo. Al hacer click sobre un nodo
obtendremos sobre un control etiqueta, Label1.Caption, la informacion referenciada. Si hacemos
click sobre el nodo hijo Amigos3 se verá como resultado...
The TreeView control is a hierarchical list of related Node objects. The user can expand and
collapse these node families easily while navigating through the control; depicting the trees and
expanding and contracting the nodes are handled automatically by the TreeView control itself.
An example of a TreeView control used in an application is the Windows Explorer program,
where the TreeView occupies the left side of the form.
Tip: The TreeView control is contained in the Windows Common Controls (COMCTL32.OCX )
that come with Visual Basic Professional and Enterprise editions.
Control Tasks
The following categories reflect the tasks that are executed when creating a TreeView.
Set Properties
Style
There are eight variations to the appearance of the TreeView. Basically, they control whether
there are pictures, plus and minus symbols, and lines. The following table, as well as Figure 5-58,
show how each value for the Style property affects the look of the TreeView:
When the Style selected includes lines, the LineStyle property controls whether the lines start at
the top-level nodes (0-tvwTreeLines) or at the root above the top-level nodes (1-tvwRootLines).
Figure 5-59 shows how the value of the LineStyle property affects the appearance of the
TreeView control.
Figure 5-59. The LineStyle property of the TreeView control
Indentation
The width by which each new child node is indented from its parent node.
ImageList
The name of an ImageList control on the same form as the TreeView. Each node placed in the
ListView can choose which image to use from the ImageList.
LabelEdit
By default, the Text property of each node can be edited by the user simply by clicking on the
caption of the selected node. In this case, the LabelEdit property is set to 0-tvwAutomatic. When
set to 1-tvwManual, the caption can be edited by the user only after the StartLabelEdit method
is called.
Sorted
Because of its hierarchical nature, the TreeView itself cannot really be sorted. However, when
the Sorted property is set to True, all Node objects with the same parent node are sorted
alphabetically. This is a global property that affects all nodes in the TreeView; each node,
however, also has a Sorted property that controls whether its child nodes are sorted.
3. Create Nodes.
Each item in a TreeView is a Node object and therefore is part of the Nodes collection. Node
objects cannot be created at design time. At runtime, they can be created by using the Add
method of the Nodes collection. This also allows the program to set some of the node's
properties. Its syntax is:
image, selectedimage)
All of these arguments except key are discussed in the following section, "Set node
properties." key represents a unique string by which a reference to the node can be
retrieved from the Nodes collection's Item property.
The caption of the node and the index or key of the ListImage to use for both unselected and
selected nodes can be set either as parameters of the Nodes collection's Add method or by
assigning values to these properties.
Relative, Relationship
These are not actually properties. However, as parameters of the Nodes collection's Add
method, they are used to position the new node in the TreeView and therefore to set
properties. When you are adding a node, Relative represents another node that is somehow
related to the node being added. Relationship denotes how the two nodes are related. When
the Relationship parameter is set to 0-tvwFirst, 1-tvwLast, 2-tvwNext, or 3-tvwPrevious, the new
node is placed at the same level as the Relative node (i.e., both have the same parent), but
either as the first or last node at that level or just after or just before the Relative node,
respectively. When set to 4-tvwChild, the new node becomes a child node of the Relative node.
Note that when adding a child node, you can choose between defining it in relationship to its
parent or to the other child nodes.
Expanded
When the Expanded property is set to True, any child nodes are revealed. When set to False,
they are hidden.
ExpandedImage
Optionally, a node can display a different image when it is expanded than when it is collapsed.
The Index or Key of the desired ListImage in the related ImageList can be used in the
ExpandedImage property.
The SelectedItem property of the TreeView returns the currently selected Node object. The
Selected property of a Node object returns a Boolean value indicating whether that node is
currently selected. By retrieving the SelectedItem property or iterating the Nodes collection and
examining each Node object's Selected property, you can determine which node is selected. By
assigning a new Node object to the SelectedItem property or by assigning True to a Node
object's Selected property, you can change the selected node programmatically.
Typically, in response to a user action such as a click, it is necessary for your application
to navigate to or from the current node. This can be done with the following properties:
Parent
The Node object's Parent property returns the node that is above the current node in the
hierarchy. When you are changing this property to a new node, all child nodes of the node being
changed remain connected. Any change that would result in a node becoming its own
descendant will rip a hole in the time-space continuum (or cause an error).
Root
The Node object's Root property returns the node that is the topmost in the node's hierarchy.
FullPath
Provides the full path from the top-level node to the referenced node. The path separator used
to delimit individual nodes is defined by the TreeView control's PathSeparator property; its
default value is a backslash (\).
Children, Child
The Children property of a node returns its number of child nodes. The Child property returns
the first child node. If the Child property is referenced for a node with no child nodes, an error
will occur. Therefore, you should always check the Children property first.
Each of these properties returns a node at the same level as the node being referenced. The
node returned is denoted by the property name. These properties are useful for "walking"
through nodes at the same level, as in this example:
Figure 5-60 displays a TreeView control with six node objects. Some of the relationships
between the nodes include the following:
Node1.Child = Node2
Node2.FirstSibling = Node2
Node2.Next = Node3
Node2.LastSibling = Node6
Node6.Previous = Node3
Figure 5-60. Node relationships
Useful Methods
HitTest
When provided with x and y coordinates, the HitTest method will return a Node object if there is
one at those coordinates. Otherwise, Nothing will be returned. The syntax of HitTest is:
StartLabelEdit
When the StartLabelEdit method is called, the caption of the node becomes both editable by the
user and selected. This is unnecessary when the LabelEdit property is set to tvwAutomatic.
Expand, Collapse
When a node is expanded or collapsed, whether through code or by the user, the Expand or
Collapse event is fired. This is fired after the node has been visibly expanded or collapsed.
However, the Expanded property can be used to reverse this action, as in this example:
When a node is clicked by the user, the NodeClick event is fired. This event also passes the
clicked node as a parameter to the event handler.
Example
The following example uses many of the conventions mentioned in this section. Figure 5-61
shows the form produced by this code.
Option Explicit
'For this example, create the following controls: _
a TextBox named txtTotal with the MultiLine _
property set to True and the Alignment _
property set to vbRightJustify, _
an ImageList named imlIcons, and _
a TreeView named tvwMain.
'Set up TreeView
Me.tvwMain.Style = tvwTreelinesPlusMinusPictureText
'This is actually the default
Me.tvwMain.ImageList = imlIcons
GetFoodRecords
Me.Caption = "Restaurant"
Me.Height = 3600
Me.Width = 5175
End Sub
Private Sub Form_Resize()
If Me.ScaleHeight < 1000 Or Me.ScaleWidth < 1000 Then
Exit Sub
End If
Me.tvwMain.Move _
120, _
120, _
Me.ScaleWidth * 0.6 - 180, _
Me.ScaleHeight - 240
lstMain.Move _
Me.ScaleWidth * 0.6 + 60, _
120, _
Me.ScaleWidth * 0.4 - 180, _
Me.ScaleHeight - 655
Me.txtTotal.Move _
Me.ScaleWidth * 0.6 + 60, _
Me.ScaleHeight - 435, _
Me.ScaleWidth * 0.4 - 180, _
315
End Sub
Private Sub tvwMain_DblClick()
Dim sItem As String
Interactions
Action Result
A node is expanded or collapsed either through code (by settings The Expand or Collapse event
its Expand property) or by the user. is fired.
User clicks on the caption of the selected node. LabelEdit property BeforeLabelEdit event is
is set to tvwAutomatic. fired.
User finishes editing the caption. AfterLabelEdit event is fired.