C# Windows Forms TreeView Examples

Let us look at a simple C# Windows Forms TreeView example.

Example 1: TreeView

This example will comprise the following files:

  • TreeView.cs

Step 1: Create Project

  1. The first step is to create a C# Project.
  2. Go to FILE-->New-->Project to create a new project.

Step 2: Write Code

Write Code as follows:

*(a). TreeView.cs

Create a file named TreeView.cs

Here is the full code

using System;
using System.Windows.Forms;

namespace Examples {
  class MainForm : Form {
    public static void Main() {
      Application.EnableVisualStyles();
      Application.Run(new MainForm());
    }

    public MainForm() {
      Text = "TreeView example";
      ClientSize = new System.Drawing.Size(300, 300);

      treeView.Parent = this;
      treeView.Location = new System.Drawing.Point(10, 10);
      treeView.Size = new System.Drawing.Size(150, 200);
      treeView.CheckBoxes = true;
      treeView.Nodes.Add("Root");
      treeView.Nodes[0].Nodes.Add("First");
      treeView.Nodes[0].Nodes[0].Nodes.Add("Second");
      treeView.Nodes[0].Nodes[0].Nodes[0].Checked = true;
      treeView.Nodes[0].Nodes[0].Nodes.Add("Third");
      treeView.Nodes[0].Nodes.Add("Fourth");
      treeView.Nodes[0].Nodes[1].Nodes.Add("Fifth");
      treeView.Nodes[0].Nodes[1].Nodes.Add("Sixth");
      treeView.Nodes[0].Nodes[1].Nodes[1].Checked = true;
      treeView.Nodes[0].Nodes[1].Nodes.Add("Seventh");
      treeView.ExpandAll();
    }

    private TreeView treeView = new TreeView();
  }
}

Run

Simply copy the source code into your C# Project,Build and Run. Alternatively download the code using the links provided below, then open the .csproj project, build and run.

Reference

Download the code using the below links:

Number Link
1. Download Example
2. Follow code author

Related Posts