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.
- Create Custom List named “
CategoryDetails
”:
- Create Column “Category Name” of type single line of text. Make it as required field and check Yes for Enforce Unique values.
- Create column “Parent Category” of type lookup. under Additional Column Settings.
Get information dropdown, select “CategoryDetails
”.
In this column dropdown, select “Category Name”:
- Example List data:
List and data ready for building tree….
- 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";
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;
}
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.