Vinit Patel

Display Hierarchical Data with TreeView in ASP.NET 2.0

Posted on: October 6, 2009


I’m going to provide a simple example how to display hierarchical data

from SQL Server database in the TreeView. A requirement is that the

implementation should not be dependant on the hierarchy level in the

database. It means that the TreeView implementation should be capable

of displaying data from any level, no matter how deep.

TreeviewEx.aspx

<asp:treeview id="tvCategoryList" runat="server" imageset="BulletedList3"
width="100%"

    showexpandcollapse="True" nodewrap="True"
     ontreenodepopulate="tvCategoryList_TreeNodePopulate"

    expanddepth="2" populatenodesfromclient="False">

    <ParentNodeStyle Font-Bold="True" />

    <RootNodeStyle Font-Bold="True" 
         CssClass="Table_Title_Label_Black12" />

    <HoverNodeStyle Font-Underline="True"
             ForeColor="#5555DD" />

    <SelectedNodeStyle Font-Underline="True"
       HorizontalPadding="0px" VerticalPadding="0px"
         ForeColor="#5555DD" />

    <NodeStyle Font-Names="Verdana" Font-Size="8pt"
      ForeColor="Black" HorizontalPadding="0px" 
      NodeSpacing="0px" VerticalPadding="0px" />

</asp:treeview>

 

Treeview.aspx.cs

protected void Page_Load(object sender, EventArgs e)

{

    if (!IsPostBack)

    {

        PopulateRootLevel();

    }

}

This happens by connecting to the database, querying the first 
set of nodes (having null as the parent id), and creating 
TreeNode objects with the PopulateNodes routine, which 
follows next.

private void PopulateRootLevel()
{

    DataTable dt = BAL_Category.GetParentCategory();
// Get Parent CategoryList From Database 
    PopulateNodes(dt, tvCategoryList.Nodes);
}

Next, we want to create the routine to populate the

child nodes of a given node. This happens with the

PopulateSubLevel method.

private void PopulateSubLevel(int parentid, TreeNode parentNode)

{

    // Get CategoryList by ParentID From Database 

    DataTable dt = BAL_Category.GetChildCategory(parentid);

    PopulateNodes(dt, parentNode.ChildNodes);

}

Here, the idea is the same as with the root level, but with

the distinction that only child nodes of the given node are

queried and populated with the PopulateNodes method

(described earlier).
The trick to triggering the populating of the child nodes

is as follows.

protected void tvCategoryList_TreeNodePopulate
        (object sender, TreeNodeEventArgs e)

{

    PopulateSubLevel(Int32.Parse(e.Node.Value), e.Node);

}

TreeNodePopulate is raised for a TreeNode which is expanded

by the user for the first time. Due to

PopulateNodesFromClient (TreeView) and PopulateOnDemand
(TreeNode) settings, this happens with the client-side callback

mechanism which is handled by the ASP.NET Page framework.

This means that populating does not
involve a postback. And, due to better cross-browser support in

ASP.NET 2.0, this also works for other browsers such as Firefox.

Note that clicking on the node does
cause a postback because I haven’t modified the select action

of the populated tree nodes from the defaults.

private void PopulateNodes(DataTable dt, 
                               TreeNodeCollection nodes)

{

    foreach (DataRow dr in dt.Rows)

    {

        TreeNode tn = new TreeNode();

        tn.Text = dr["Category"].ToString();

        tn.Value = dr["CategoryID"].ToString();

        int NoofChild = 
        Convert.ToInt32(dr["childnodecount"].ToString());

        if (NoofChild != 0 )

        {

            tn.PopulateOnDemand = true;

            tn.SelectAction = TreeNodeSelectAction.None;

        }

        else

        {

            tn.PopulateOnDemand = false;

      if (dr["TotalDoc"].ToString().Equals("0") == false)

            {

          tn.NavigateUrl = 
        "~/CategoryWiseProductList.aspx?ID=" 
            + dr["CategoryID"].ToString();

           tn.Text = tn.Text + 
            " (" + dr["TotalProduct"].ToString() + ")";

            }

            else

            {

          tn.NavigateUrl = 
 "javascript:alert('Product is not Available Under this Category.')";

            }

        }

        nodes.Add(tn);

    }

}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Calendar

October 2009
M T W T F S S
« Sep   Dec »
 1234
567891011
12131415161718
19202122232425
262728293031  

Stats Of Blog

  • 6,824 hits

Cluster Map

%d bloggers like this: