Search This Blog

Thursday, May 12, 2016

Show a document library hierarchy in a tree view

Objective:

To programmatically build a tree view that shows a specific document library.
Solution:
To achieve this goal, SharePoint offers the classes:
SPHierarchyDataSourceControl
SPTreeView
With SPHierarchyDataSourceControl you can build the entire hierarchy of you web. In this case we need 
to limit it to a single document library.
Build a new Web Part and override the CreateChildControls method with the following code, modifying 
the data source with your needed:

protected override void CreateChildControls()
{
           
        SPDocumentLibrary docLib = GetDocLib(SPContext.Current.Web.ServerRelativeUrl, "Shared Documents");
        //change GetDocLib with your code to get a SPDocumentLibrary object

SPHierarchyDataSourceControl myDataSource = new SPHierarchyDataSourceControl();
myDataSource.ID = "myTreeViewDataSource";
myDataSource.RootContextObject = "Web";
        myDataSource.IncludeDiscussionFolders = false;
        myDataSource.ShowDocLibChildren = true;
        myDataSource.ShowFolderChildren = true;
        myDataSource.ShowListChildren = false;
        myDataSource.ShowWebChildren = false;
        myDataSource.Web = SPContext.Current.Web;
        myDataSource.RootWebId = SPContext.Current.Web.ID.ToString();
        myDataSource.RootContextObject = null;
        myDataSource.RootListId = docLib.ID.ToString();
           

        SPTreeView myTreeView = new SPTreeView();
        myTreeView.ID = "myTreeView";
        myTreeView.DataSourceID = "myTreeViewDataSource";
        myTreeView.EnableClientScript = true;
        myTreeView.EnableViewState = true;
        myTreeView.NodeIndent = 12;
        myTreeView.NodeStyle.CssClass = "ms-navitem";
        myTreeView.NodeStyle.HorizontalPadding = 2;
        myTreeView.SelectedNodeStyle.CssClass = "ms-tvselected";
        myTreeView.ExpandDepth = 0;
        myTreeView.ExpandImageUrl = 
        SPUrlUtility.CombineUrl(SPContext.Current.Web.ServerRelativeUrl, "/_layouts/images/tvplus.gif");

        myTreeView.CollapseImageUrl =
        SPUrlUtility.CombineUrl(SPContext.Current.Web.ServerRelativeUrl, "/_layouts/images/ tvminus.gif");

        myTreeView.NoExpandImageUrl = 
       SPUrlUtility.CombineUrl(SPContext.Current.Web.ServerRelativeUrl, "/_layouts/images/ tvblank.gif");

        myTreeView.SkipLinkText = "";
        myTreeView.ShowLines = true;
        Controls.Add(myTreeView);
}

No comments:

Post a Comment