Skip to main content

Thinking out aloud - Dave Hunter's SharePoint Blog

Go Search
Home
Blog
  

Locations of visitors to this page


 Useful Links

  Microsoft UK events
  SharePoint 2007 on CodePlex
  SharePoint Community Portal
  SharePoint User Group
  SharePoint Community Portal
  SharePoint Pedia
  SharePoint MSDN Forums
  SharePoint University
Home > Thinking out aloud - Dave Hunter's SharePoint Blog > Posts > Creating a Tree View Control WebPart
My thoughts and findings on Microsoft Information worker technologies, including MCMS and SharePoint 2007 (MOSS).
Creating a Tree View Control WebPart

I had a requirement to create a tree view control to rollup document libraries into a single view.  I chose to use the System.Web.UI.WebControls.TreeView web control.

Once you define the tree view control you add nodes, for example:

TreeNode childNode = new TreeNode(file.Name, "", "~/_layouts/images/" + file.IconUrl, file.ServerRelativeUrl.ToString(), "");
treeView.ChildNodes.Add(childNode);

 

I wanted to get all document libraries for a current web, I used the SPWeb.GetListsOfType method, this takes in a SPBaseType enumeration.  For example:

currentWeb.GetListsOfType(SPBaseType.DocumentLibrary)

I wrote a recursive function which loops through all the root document libraries and loops through their folders.  This looked like:

foreach(SPList list in currentWeb.GetListsOfType(SPBaseType.DocumentLibrary))
{
  // build the tree
  rootNode = new System.Web.UI.WebControls.TreeNode(list.Title, "", "~/_layouts/images/itdl.gif", list.RootFolder.ServerRelativeUrl.ToString(), ""); 

  // loop down the tree
  TraverseFolder(list.RootFolder, rootNode); 

  // add the root node to tree view
  treeView.Nodes.Add(rootNode); 

}

The completed webpart looks like:

 Tree View Web Part

Here's the code:

#region namespaces
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; 

using Microsoft.SharePoint;
using System.Web.UI.WebControls.WebParts;
using AspControls = System.Web.UI.WebControls;
using System.Web.Caching;
#endregion 

namespace Dhunter.SharePoint.Controls
{
    public class DocumentLibraryViewerWebPart : System.Web.UI.WebControls.WebParts.WebPart
    {
        #region controls
        protected System.Web.UI.WebControls.TreeView treeView;
        private AspControls.TreeNode rootNode;
        #endregion 

        #region members
        private string listNamesToExclude = "Site Template Gallery;Converted Forms;Form Templates;
Images;Pages;Reporting Templates;Master Page Gallery;Site Collection Images;Site Collection Documents;
Style Library;List Template Gallery;PublishingImages;Web Part Gallery"
; private string userDefinedListNamesToExclude = ""; #endregion #region public properties /// <summary> /// List Name Exclusions /// </summary> [WebBrowsable(true), WebDisplayName("List Names to Exclude"), WebDescription("Names of lists that shouldn't be shown in the viewer in this site"), Personalizable(PersonalizationScope.Shared)] public string UserDefinedListNamesToExclude { get { return userDefinedListNamesToExclude; } set { userDefinedListNamesToExclude = value; } } #endregion #region constructor /// <summary> /// Constructor /// </summary> public DocumentLibraryViewerWebPart() { // set the export mode this.ExportMode = System.Web.UI.WebControls.WebParts.WebPartExportMode.All; } #endregion #region utility methods /// <summary> /// Checks if the List should be excluded (hidden) /// </summary> /// <param name="listName"></param> /// <returns></returns> private bool ExcludeListName(string listName) { string[] arr = listNamesToExclude.Split(Convert.ToChar(";")); bool isPresent = arr.Contains(listName); if (isPresent == false) { string[] userDefArr = UserDefinedListNamesToExclude.Split(Convert.ToChar(";")); isPresent = userDefArr.Contains(listName); } if (isPresent) Console.WriteLine(listName); return isPresent; } #endregion #region overriden methods /// <summary> /// Create the child controls /// </summary> protected override void CreateChildControls() { // get the current site SPSite currentSite = SPContext.Current.Site; using (SPWeb currentWeb = currentSite.OpenWeb()) { // set the tree view properties treeView = new System.Web.UI.WebControls.TreeView(); treeView.ShowLines = true; // show lines treeView.ExpandDepth = 0; // expand non treeView.CssClass = "docLibViewer"; // set the class // loop through the lists of the current web // only show document libraries foreach (SPList list in currentWeb.GetListsOfType(SPBaseType.DocumentLibrary)) { // only show document libraries that haven't been excluded by the system document libraries or by the user exclusion (via the webpart properties) if (!ExcludeListName(list.Title)) { // build the tree rootNode = new System.Web.UI.WebControls.TreeNode(list.Title, "", "~/_layouts/images/itdl.gif",
list.RootFolder.ServerRelativeUrl.ToString(), ""); // loop down the tree TraverseFolder(list.RootFolder, rootNode); // add the root node to tree view treeView.Nodes.Add(rootNode); } } } this.Controls.Add(treeView); base.CreateChildControls(); } /// <summary> /// Render Contents /// </summary> /// <param name="writer"></param> protected override void RenderContents(System.Web.UI.HtmlTextWriter writer) { // render the control base.RenderContents(writer); } #endregion #region public methods /// <summary> /// Loop through the folders /// </summary> /// <param name="folder"></param> /// <param name="node"></param> public void TraverseFolder(SPFolder folder, AspControls.TreeNode node) { // create a new node AspControls.TreeNode newNode = new System.Web.UI.WebControls.TreeNode(folder.Name, "", "~/_layouts/images/itdl.gif",
folder.ServerRelativeUrl.ToString(), ""); try { // don't add the forms folder if (folder.Name != "Forms") { // loop through all child folders foreach (SPFolder childFolder in folder.SubFolders) { // don't add the forms folder if (childFolder.Name != "Forms") { // create a new node and recurse AspControls.TreeNode trn = new System.Web.UI.WebControls.TreeNode(childFolder.Name, "",
"~/_layouts/images/itdl.gif", childFolder.ServerRelativeUrl.ToString(), ""); newNode = TraverseFiles(childFolder, trn); // add the new node to the tree rootNode.ChildNodes.Add(newNode); } } // loop through the files foreach (SPFile childFile in folder.Files) { // create a new node and add to the tree AspControls.TreeNode childNode = new System.Web.UI.WebControls.TreeNode(childFile.Name + " (" + childFile.TimeLastModified.ToShortDateString()
+ ")", "", "~/_layouts/images/" + childFile.IconUrl, childFile.ServerRelativeUrl.ToString(), ""); rootNode.ChildNodes.Add(childNode); } } } catch (Exception e) { //TODO: handle error } } /// <summary> /// Loop through the files /// </summary> /// <param name="fldr"></param> /// <param name="node"></param> /// <returns></returns> public AspControls.TreeNode TraverseFiles(SPFolder folder, AspControls.TreeNode node) { try { // add the files contained in this folder foreach (SPFile file in folder.Files) { // create a new node and add to the tree AspControls.TreeNode childNode = new System.Web.UI.WebControls.TreeNode(file.Name + " (" + file.TimeLastModified.ToShortDateString()
+ ")", "", "~/_layouts/images/" + file.IconUrl, file.ServerRelativeUrl.ToString(), ""); node.ChildNodes.Add(childNode); } // test if we have child folders bool blnRecurseFolders = folder.SubFolders.Count > 0 ? true : false; // if we have sub folders then loop through them if (blnRecurseFolders) { // loop through the child folders foreach (SPFolder childFolder in folder.SubFolders) { // create a new node and loop through the files AspControls.TreeNode childNode = new System.Web.UI.WebControls.TreeNode(childFolder.Name); node.ChildNodes.Add(TraverseFiles(childFolder, childNode)); } } } catch (Exception e) { //TODO: handle error } return node; } #endregion } }
  Copyright
This work is licenced under a Creative Commons Attribution-Noncommercial-No Derivative Works 2.0 UK: England & Wales License
  Site Map

Comments

Nice Article..

This is very Helpful .Thanks a lottt
at 21/08/2009 07:48

Treeview control

Thank you very much for this! Very helpful.
at 07/09/2009 10:38

Thanks for the post

Hi Mate, this post saved me hours and hours of frustration. Good stuff! and thank you :)
at 08/10/2009 07:34

 Dave Hunter

I'm currently a Senior Consultant at Netstore 2e2. I specialise in Microsoft Information Worker technologies (especially MOSS, MCMS and .NET), with over 8 years of experience within this area of specialism. 

I have gained two certifications for MOSS and WSS and look to complete the full certification track soon.

View Dave Hunter's profile on LinkedIn

  Subscribe in a reader


 Latest Posts

I’ve been Awarded a MVP for SharePoint01/04/2010 19:49
SharePoint 2010 Training on Microsoft E-Learning15/03/2010 17:56
SharePoint UK User Group - Thursday 27th August London Meeting25/08/2009 17:56
CAML Query that filters on the current user23/07/2009 17:50
Microsoft Ramp Up Free SharePoint Developer Training22/07/2009 20:59
How To: Change a SharePoint Application Pool Programmatically07/07/2009 18:08
SharePoint Forums Topping 100 Answers06/07/2009 12:29
Find out the SharePoint Internal Name for a Column or Site Column28/05/2009 09:56
Delving into Deploying SharePoint Artifacts with Features24/04/2009 15:20
SharePoint - Connecting MySites with the Portal24/04/2009 14:39
1 - 10 Next