Click here to Skip to main content
15,867,568 members
Articles / Productivity Apps and Services / Sharepoint
Tip/Trick

Build Tree View Structure for SharePoint List Data

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
28 Jul 2013CPOL1 min read 50.6K   622   6   6
How to build treeview structure for SharePoint List data

Introduction 

In our project, we had a requirement that all category / sub category details will be stored in a list named “CategoryDetails”. Category / sub category details should be shown in tree structure for end users.

This tip contains list details for storing category / sub category data and code to build tree structure for the same.

  1. Create Custom List named “CategoryDetails”:

    Image 1

  2. Create Column “Category Name” of type single line of text. Make it as required field and check Yes for Enforce Unique values.

    Image 2

  3. Create column “Parent Category” of type lookup. under Additional Column Settings.

    Get information dropdown, select “CategoryDetails”.

    In this column dropdown, select “Category Name”:

    Image 3
  4. Example List data:

    Image 4

    List and data ready for building tree….

  5. Now we will look for the code to build tree structure for the list data using ASP tree view control.

    Create Empty SharePoint project and add a visual webpart named “TreeStructure”.

    “The code first looks for items where parent is null, i.e., Top level items like India, America..

    Then for each top level items, child items will be fetched by using query where parent is India, America like that.

    The same method will be called recursively to get all child items.”

    In “TreeStructureUserControl.ascx”, add an ASP treeview control.

    ASP.NET
    <asp:TreeView ID="treeViewCategories" 
    runat="server"></asp:TreeView>

TreeStructureUserControl.ascx.cs adds the below code and deploy the solution:

C#
public const string DYNAMIC_CAML_QUERY = 
"<Where><IsNull><FieldRef Name='{0}' /></IsNull></Where>";
        public const string DYNAMIC_CAML_QUERY_GET_CHILD_NODE = 
        "<Where><Eq><FieldRef Name='{0}' />
        <Value Type='LookupMulti'>{1}</Value></Eq></Where>";
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                BuildTree();         
            }
        }
        protected void BuildTree()
        {
            SPList TasksList;
            SPQuery objSPQuery;
            StringBuilder Query = new StringBuilder();
            SPListItemCollection objItems;
            string DisplayColumn = string.Empty;
            string Title = string.Empty;
            string[] valueArray = null;
            treeViewCategories.Nodes.Clear();
            try
            {
                using (SPSite site = new SPSite(SPContext.Current.Web.Url))
                {
                    using (SPWeb web = site.OpenWeb())
                    {

                        TasksList = SPContext.Current.Web.Lists["CategoryDetails"];
                        if (TasksList != null)
                        {

                            objSPQuery = new SPQuery();
                            Query.Append(String.Format(DYNAMIC_CAML_QUERY, "Parent Category"));
                            objSPQuery.Query = Query.ToString();
                            objItems = TasksList.GetItems(objSPQuery);
                            if (objItems != null && objItems.Count > 0)
                            {
                                foreach (SPListItem objItem in objItems)
                                {
                                    DisplayColumn = Convert.ToString(objItem["CategoryName"]);
                                    Title = Convert.ToString(objItem["CategoryName"]);
                                    CreateTree(Title, valueArray, null, 
                                    DisplayColumn, objItem["ID"].ToString());
                                }
                            }
                        }
                    }
                }               
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }
        private void CreateTree(string RootNode, string[] valueArray, 
        List<SPListItem> objNodeCollection, string DisplayValue, string KeyValue)
        {
            string objExpandValue = string.Empty;
            TreeNode objTreeNode;
            TreeNodeCollection objChildNodeColn;
            try
            {              
                objTreeNode = new TreeNode(DisplayValue, KeyValue);
                treeViewCategories.Nodes.Add(objTreeNode);
                objTreeNode.CollapseAll();
                objChildNodeColn = GetChildNode(RootNode, valueArray, objNodeCollection);
                foreach (TreeNode childnode in objChildNodeColn)
                {
                    objTreeNode.ChildNodes.Add(childnode);
                }               
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private TreeNodeCollection GetChildNode(string RootNode, 
        string[] valueArray, List<SPListItem> objListItemColn)
        {
            TreeNodeCollection childtreenodes = new TreeNodeCollection();
            SPQuery objSPQuery;
            SPListItemCollection objItems = null;
            List<SPListItem> objNodeListItems = new List<SPListItem>();
            SiteMapNodeCollection objNode = new SiteMapNodeCollection();
            objSPQuery = new SPQuery();
            string objNodeTitle = string.Empty;
            string objLookupColumn = string.Empty;
            StringBuilder Query = new StringBuilder();
            SPList objTaskList;
            SPField spField;
            string objKeyColumn;

            try
            {            
                objTaskList = SPContext.Current.Web.Lists["CategoryDetails"];
                objLookupColumn = "Parent Category";//objTreeViewControlField.ParentLookup;

                spField = SPContext.Current.Web.Lists
                ["CategoryDetails"].Fields["Parent Category"];

                Query.Append(String.Format
                (DYNAMIC_CAML_QUERY_GET_CHILD_NODE, spField.InternalName, RootNode));
                objSPQuery.Query = Query.ToString();

                objItems = objTaskList.GetItems(objSPQuery);
                foreach (SPListItem objItem in objItems)
                {
                    objNodeListItems.Add(objItem);
                }
               
                if (objNodeListItems != null && objNodeListItems.Count > 0)
                {
                    foreach (SPListItem objItem in objNodeListItems)
                    {
                        RootNode = Convert.ToString(objItem["CategoryName"]);
                        objKeyColumn = Convert.ToString(objItem["ID"]);

                        objNodeTitle = Convert.ToString(objItem["CategoryName"]);
                        if (!String.IsNullOrEmpty(objNodeTitle))
                        {
                            TreeNode childNode = new TreeNode();
                            childNode.Text = objNodeTitle;
                            childNode.Value = objKeyColumn;
                            childNode.CollapseAll();
                            foreach (TreeNode cnode in GetChildNode
                            (RootNode, valueArray, objListItemColn))
                            {
                                childNode.ChildNodes.Add(cnode);

                            }
                            childtreenodes.Add(childNode);
                        }
                    }
                }               
            }
            catch (Exception ex)
            {              
                throw ex;
            }
            return childtreenodes;
            // Call method again (recursion) to get the child items
        }

Now add “Treestructure” web part in any page… tree structure for the above example data will be displayed as below:

Image 5

The complete source code is attached.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionIt's not working for me (empty) Pin
Member 1394864824-Nov-18 5:36
Member 1394864824-Nov-18 5:36 
QuestionBuild Tree View Structure for SharePoint List Data Pin
Member 1340873213-Sep-17 15:37
Member 1340873213-Sep-17 15:37 
QuestionIts not Working for me.... Pin
Member 1247489320-Apr-16 21:37
Member 1247489320-Apr-16 21:37 
QuestionThis did not work for me Pin
Member 1103762426-Aug-14 5:05
Member 1103762426-Aug-14 5:05 
QuestionTreeview for List SharePoint Pin
Анна Пожидаева22-Oct-13 21:23
Анна Пожидаева22-Oct-13 21:23 
QuestionHow do I get another field from the same list to appear at the a different web part on the same page Pin
cally213-Aug-13 18:04
cally213-Aug-13 18:04 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.