Click here to Skip to main content
Click here to Skip to main content

Tagged as

Build Tree View Structure for SharePoint List Data

, 28 Jul 2013 CPOL
Rate this:
Please Sign up or sign in to vote.
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”:

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

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

    Get information dropdown, select “CategoryDetails”.

    In this column dropdown, select “Category Name”:

  4. Example List data:

    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:TreeView ID="treeViewCategories" 
    runat="server"></asp:TreeView>

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

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:

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)

Share

About the Author

Rachana BG

United States United States
No Biography provided

Comments and Discussions

 
QuestionThis did not work for me PinmemberMember 1103762426-Aug-14 6:05 
QuestionTreeview for List SharePoint PinmemberАнна Пожидаева22-Oct-13 22:23 
QuestionHow do I get another field from the same list to appear at the a different web part on the same page Pinmembercally213-Aug-13 19:04 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.1411019.1 | Last Updated 28 Jul 2013
Article Copyright 2013 by Rachana BG
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid