Home » ASP.Net, C# Codes, Tech Corner

Populating ASP.NET TreeView Control from DataBase

27 October 2009 No Comments Posted By:Vivek

Here i will explain the binding of a treeview from the Database.This can be a tricky task since we may have to build a parent-child relationship here.So first thing you would need is a table in the database where we actually have the parent-child relationship.
An Example
Table Name: Category
CategoryId  INT
CategoryName  Varchar(50)
ParentCategoryId INT
NodeLevel  INT

Suppose we have Data in the Table named Category as follows

1 Root NULL 0
2 Child 1 1
3 Child2 1 1
4 grandChild 2 2
5 grandChild2 2 2
6 grandChild3 3 2



Now to bind this to the tree,we will use a recursive function.Also for better performance,we will bind the database results into a global DataTable first and then apply filtering.

Here is the Code to bind to the DataTable.

 private void bindDataTable()
    {
       
        string strConn = ConfigurationManager.ConnectionStrings["yourConnectionName"].ConnectionString;
        SqlConnection conn = new SqlConnection(strConn);
        SqlCommand cmd = new SqlCommand("Select * from Category", conn);
        cmd.CommandType = CommandType.Text;
       
        SqlDataAdapter sqlDa = new SqlDataAdapter();
        sqlDa.SelectCommand = cmd;
        sqlDa.Fill(dt);
        conn.Close();

    }

Now we will add a recursive method that will make use of this DataTable to build the TreeView.

private void buildNodes(TreeNode n, int? categoryId)
    {
        DataRow[] drCategories;
        if (categoryId == null)
            drCategories = dt.Select("NodeLevel=0"); // This will get the Root Node
        else
            drCategories = dt.Select("ParentIdFK='" + categoryId + "'");

        foreach (DataRow dr in drCategories)
        {
            TreeNode t = new TreeNode();
            t.Text = dr["CategoryName"].ToString();
            t.Value = dr["CategoryId"].ToString();    
           
            buildNodes(t, Convert.ToInt32(dr["CategoryId"].ToString()));// Calling the function resursively
            if (n == null)// If it is Root Node
                TreeView1.Nodes.Add(t);
            else
                n.ChildNodes.Add(t);

        }

Above we are using int? so that int type can accept null values.

So now all we have to do is call these methods.

  protected void Page_Load(object sender, EventArgs e)
     {
         if (!IsPostBack)
         {
              bindDataTable();
              buildNodes(null, null);//CategoryId=null is passed which is the ParentId of the Root Node
         }
     }

Now you can add some formatting and Css as you may please to get a better looking Treeview.Happy Coding Folks!!!

Related posts:

  1. How to Bind Images from Database in a GridView
  2. Edit,Update,Cancel In a GridView
  3. Dropdownlist inside a Gridview
  4. Creating your first WebService using .NET
  5. Multiview and View controls in ASP.NET(3.5)

Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>