Whenever you need to display hierarchical data in a tree-like format in VB.NET, you should use the TreeView control. In this tip, Irina Medvinskaya presents an example that uses the TreeView control for Windows-based applications.
If you need to show hierarchical data in a tree-like format in VB.NET, you should use the TreeView control. This flexible control allows you to change numerous properties in order to fit your needs. The TreeView control also lets you add nodes and sub-nodes; you have the option of adding the nodes in design-time, but you will usually do this in run-time.
Example: Using TreeView for Windows-based applications
To add the TreeView control to your form, open the Toolbox, find the TreeView control under the Common controls section, and double-click it.To add the nodes in design time, click the Control properties and then click Nodes. You will see a screen similar to Figure A that allows you to add nodes and sub-nodes. Figure A
To add nodes in run-time, run the following example. First, add this code to the form load event:
Then add this event:
Private Sub TreeView1_AfterSelect(ByVal sender As System.Object, ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles TreeView1.AfterSelectThe result will look like Figure B. Figure B
Here are notes about the example code:
- I add the code to prevent the control from being refreshed.
- I add the first node by using the Nodes.Add method and passing to it the name of the node.
- I add sub-nodes to the initial node and follow this strategy for three top-level nodes.
- In order to know which node/sub-node combination is selected, I use the AfterSelect event of the TreeView control and use the MessageBox to display the SelectedNode.FullPath.
Learn more about the TreeView control
There are a number of properties that you can set up for the TreeView control in order to fit your needs both in behavior and display. The control lets you show check boxes or icons next to the nodes' names, displaying plus/minus signs, and a number of other options. Visit MSDN for more information about using the TreeView control.
Irina Medvinskaya has been involved in technology since 1996. She has an MBA from Pace University and works as a project manager at Citigroup.
----------------------------------------------------------------------------------------Get Visual Basic tips in your inbox
Advance your scripting skills to the next level with TechRepublic's free Visual Basic newsletter, delivered each Friday. Automatically subscribe today!