Bind Datatable to Treeview Using C#

This tutorial will teach you how to bind Datatable to a Treeview using C#. For this tutorial, We will use a dynamically created datatable with sample data to understand the topic better.

How to Bind Datatable to Treeview Using C#

First, create a WinForm Application using your preferred version of Visual Studio. Once the application is created, add a Treeview control to it with the following properties:

Name: myTreeView

Treeview Control

Create the Datatable

As mentioned above, we will create a datatable and add a few records. Use the code below to create the datatable;

public DataTable CreateDataTableEmployees()
    DataTable dataTable = new DataTable();

    // Add few records to the datatable
    dataTable.Rows.Add("IT", "Fred");
    dataTable.Rows.Add("IT", "Mike");
    dataTable.Rows.Add("IT", "Natalie");
    dataTable.Rows.Add("Engineering", "Lisa");
    dataTable.Rows.Add("Engineering", "Paul");
    dataTable.Rows.Add("HR", "Scott");
    dataTable.Rows.Add("Research and Development", "Sean");
    return dataTable;

Create the Bind Tree View Function

Now, add the function below to your code:

private void BindTreeView( DataTable dataTable)
    int i = 0;
    while (i < dataTable.Rows.Count)
        DataRow row = dataTable.Rows[i];

        //Get the department
        string department = row.Field<string>(0) ?? "";

        // Add department Node
        TreeNode departmentNode = myTreeView.Nodes.Add(department);
        while (i < dataTable.Rows.Count && row.Field<string>(0) == department)
            // Get the Name
            string name = row.Field<string>(1) ?? "";

            //Add name to department Node

            while (i < dataTable.Rows.Count && row.Field<string>(0) == department && name == row.Field<string>(1))
                if (++i < dataTable.Rows.Count)
                    row = dataTable.Rows[i];

The next step is to call the function above from the Page_Load Event:

private void Form1_Load(object sender, EventArgs e)
    DataTable dataTable = this.CreateDataTableEmployees();
You can call the function from other Windows Events, such as the button event.

Run the application; the result should look like the following:

Bonus: show a message when the user selects a node

To add more action to your Treeview, you can show a node value inside a message box when a user selects the node:

private void myTreeView_AfterSelect(object sender, TreeViewEventArgs e)
   MessageBox.Show(myTreeView.SelectedNode.Text,"You have selected");

Happy Coding!

Leave a Reply

Your email address will not be published.