NinethSense oWnZ mE!: Praveen’s drawing book

Choose a Topic:

Fri
10
Oct '08

Populate ASP.NET TreeView control with hirarchial data

The code uses rescursive method to populate hirarchial data. I have used DNN - DotNetNuke database to demonstrate.


Here is the code:

(The code is not structured. Please forgive. You may even find hardcoded values)
 
 
public DataTable dt = new DataTable();
    protected void Page_Load(object sender, EventArgs e)
    {
        SqlDataAdapter da = 
               new SqlDataAdapter(“SELECT tabid, tabname, parentid FROM DNN_tabs WHERE isdeleted <> 1″, “your connection string”);
        da.Fill(dt);
 
        TreeView1.Nodes.Clear();
        TreeNode tn = new TreeNode();
        AddNodes(ref tn, “null”);
        tn.Text = “Root”;
        TreeView1.Nodes.Add(tn);
     }


 
    private void AddNodes(ref TreeNode tn, string parentid)
    {
        TreeNode ctn = new TreeNode();
        string criteria = “parentid=”+parentid;
        if (parentid == “null”) criteria = “parentid is null”;
        foreach (DataRow dr in dt.Select(criteria))
        {
            ctn = new TreeNode(dr[“tabname”].ToString());
            AddNodes(ref ctn, dr[“tabid”].ToString());
            tn.ChildNodes.Add(ctn);
        }
    }


In aspx file, just drag drop the treeview control from toolbox. The code will look like this:

< %@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

< !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

        <asp :TreeView ID="TreeView1" runat="server" NodeIndent="50" ShowLines="True">
        </asp>

    </div>
    </form>
</body>
</html>

Comments are closed.

The CodeProject Microsoft Developer Network Official ASP.NET Forums Microsoft .NET Framework Community Microsoft Most Valuable Professional Kidoos forums Microsoft Visual Studio Developer Home Professional Information Technology Solutions Microsoft Research Home Kerala Microsoft Users Group Community Website