Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

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();
    dataTable.Columns.Add("Department");
    dataTable.Columns.Add("Employee");

    // 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;
    myTreeView.Nodes.Clear();
    while (i (0) ?? "";

        // Add department Node
        TreeNode departmentNode = myTreeView.Nodes.Add(department);
        while (i (0) == department)
        {
            // Get the Name
            string name = row.Field(1) ?? "";

            //Add name to department Node
            departmentNode.Nodes.Add(name);

            while (i (0) == department && name == row.Field(1))
            {
                if (++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();
    BindTreeView(dataTable);
}
Note
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!



This post first appeared on Php Convert Array To String, please read the originial post: here

Share the post

Bind Datatable to Treeview Using C#

×

Subscribe to Php Convert Array To String

Get updates delivered right to your inbox!

Thank you for your subscription

×