C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Now: Double-click on the Form1 window in the designer so you can create the Form1_Load event.
Load: In this event handler, we will insert code to build the nodes in the TreeView control.
Info: To add the Form1_Load event, double-click on the window of the program in the Visual Studio designer.
Note: The statement "treeView1.Nodes.Add(treeNode)" adds a node instance to the treeView1 instance of the TreeView that exists.
C# program that adds to TreeView
using System;
using System.Windows.Forms;
namespace WindowsFormsApplication23
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//
// This is the first node in the view.
//
TreeNode treeNode = new TreeNode("Windows");
treeView1.Nodes.Add(treeNode);
//
// Another node following the first node.
//
treeNode = new TreeNode("Linux");
treeView1.Nodes.Add(treeNode);
//
// Create two child nodes and put them in an array.
// ... Add the third node, and specify these as its children.
//
TreeNode node2 = new TreeNode("C#");
TreeNode node3 = new TreeNode("VB.NET");
TreeNode[] array = new TreeNode[] { node2, node3 };
//
// Final node.
//
treeNode = new TreeNode("The Dev Codes", array);
treeView1.Nodes.Add(treeNode);
}
}
}
Tip: You can call the Add instance method and pass it an argument of type TreeNode to add a node to the TreeView.
Then: It creates another node and specifies that array reference as the second parameter. The nodes in the array are children nodes.
ArrayTip: To add the MouseDoubleClick event handler, right-click the TreeView in the designer and select Properties.
Then: Select "MouseDoubleClick" and click twice on that entry. You can then change treeView1_MouseDoubleClick, which was generated.
TreeView and double-clicking on nodes: C#
using System;
using System.Windows.Forms;
namespace WindowsFormsApplication23
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// Insert code here. [OMIT]
}
private void treeView1_MouseDoubleClick(object sender, MouseEventArgs e)
{
//
// Get the selected node.
//
TreeNode node = treeView1.SelectedNode;
//
// Render message box.
//
MessageBox.Show(string.Format("You selected: {0}", node.Text));
}
}
}
And: After a double-click, a node is selected so this returns a reference to that node in the object model.
Tip: If you double-click on the node "Linux", a MessageBox is shown with that text.
MessageBox