ASP.Net Code

ASP.Net 2.0 – Populate a TreeView from a Hierarchical Database

The control is perfect for implementing hierarchical structures in a User Interface, and this code will show you how to actually get the data into the control from a 'parent-child' database table. This code makes use of a recursive function.

You can read a step-by-step explanation in a tutorial I wrote.


<%@ Page Language="C#" CompileWith="tree.aspx.cs" ClassName="tree_aspx" Debug="true" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" " http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Select item from treeview</title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:TreeView ID="EmployeeList" Runat="Server" />
    </form>
</body>
</html>

and the code-behind


using System;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Configuration;
using System.Web;
using System.Web.Caching;
using System.Web.Security ;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

DataSet EmployeeDS = new DataSet();

void page_load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        // first load DataSet
        LoadDataSet();

        // now build list
        BuildEmployeeList(EmployeeList.Nodes, 0);
    }
}


void LoadDataSet()
{
    String conn = ConfigurationSettings.AppSettings["connStr"];
    String strSQL = "SELECT id, name, mgr_id FROM [employees]";
    SqlDataAdapter myAdapter = new SqlDataAdapter(strSQL, conn);
    myAdapter.Fill(EmployeeDS, "employees");
}

private void BuildEmployeeList(TreeNodeCollection nodes, Int32 IntParent)
{
    Int32 ThisID;
    String ThisName;
    DataRow[] children = EmployeeDS.Tables["employees"].Select("mgr_id='"+IntParent+"'");
    //no child nodes, exit function
if (children.Length == 0) return;

    foreach (DataRow child in children)
    {
        ThisID = Convert.ToInt32(child.ItemArray[0]);
        ThisName = Convert.ToString(child.ItemArray[1]);   
        TreeNode NewNode = new TreeNode(ThisName, ThisID.ToString());
        nodes.Add(NewNode);
        NewNode.ToggleExpandState();
        BuildEmployeeList(NewNode.ChildNodes, ThisID);
    }
}
Share

Leave a Reply

Your email address will not be published. Required fields are marked *

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Anti-spam image