Monday, July 21, 2008

Creating a Tree View WebPart for Document Library

You could develop a web part (if works for you site), and render in it a tree view for your document library. To do that, you must create a new web part project in Visual Studio 2005 (with WSS extensions), add by code an asp.net Tree View control, and add a new node for each document or folder in your library.

This below code creates a web part tree view for a document library as which specified on the code in the site:

Code:

TreeNode childNode;

//Method for Get Child Nodes for the tree view

protected void GetChildNodes(TreeNode node, SPFolder folder)
{
foreach (SPFolder subFolder in folder.SubFolders)
{
if (subFolder.Name != "Forms")
{
TreeNode auxNode = new TreeNode(subFolder.Name, "Child", "", subFolder.ServerRelativeUrl, "");
GetChildNodes(auxNode, subFolder);
node.ChildNodes.Add(auxNode);
}
}
foreach (SPFile file in folder.Files)
{
TreeNode auxNode = new TreeNode(file.Name, "Child", "", file.ServerRelativeUrl, "");
node.ChildNodes.Add(auxNode);
}
}

protected override void CreateChildControls()
{
using (SPWeb web = SPContext.Current.Web)
{
foreach (SPList documentLibrary in web.Lists)
{

//Which gets all Document Libraries in the particular site

if (documentLibrary.BaseType == SPBaseType.DocumentLibrary & documentLibrary.Hidden == false)
{

// Here Anil’s Document is as of Document Library Name. Put your Document Library name on here. On the below commented if statement for getting value from the property window ‘doclib’ as property variable.

if (documentLibrary.Title.Equals("Anil's Document"))
// if (documentLibrary.Title==doclib)
{
childNode = new TreeNode(documentLibrary.Title, "RootNode", "", documentLibrary.DefaultViewUrl, "");
GetChildNodes(childNode, documentLibrary.RootFolder);
childNode.ChildNodes.Add(childNode);
}
}
}

//Here TreeView is created with as rootnode and its subnodes.

TreeView trView = new TreeView();
trView.Nodes.Add(childNode);
trView.CollapseAll();
Controls.Add(trView);
}
base.CreateChildControls();
}
}
}


Conclusion

I try to Set the Document Library name through the Property window for display Tree View. But I fail to pass value (Document Library Name) for the TreeView. But now we can set the Document Library Name through the code for display Tree View.