Thursday, February 17, 2011

Iterating through SPweb, SPlist and populating Treeview

Following code makes a tree view for a site (web) and its child sites, their lists.
It also displays the number of items each of that list has.

It’s a small Administration utility and very helpful for understanding how to iterate through spsite, spweb and lists.

I used Visual studio 2010. Its great tool to work with SharePoint 2010.
This really a great relied in terms of developing a webpart, packaging and deploying.

I have a user control there I added a tree view, name 'tviewSiteStructure'.

using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;

namespace SiteStructure.SiteStructureWebPart
{
public partial class SiteStructureWebPartUserControl : UserControl
{
protected void Page_Load(object sender, EventArgs e)
{

using (SPSite mySite = new SPSite("http://MyMOSS2010/CP"))
{
using (SPWeb myWeb = mySite.OpenWeb())
{

TreeNode mynode = new TreeNode(myWeb.Title, null, null, myWeb.Url, "_self");
TreeNode parentNode = mynode;
tviewSiteStructure.Nodes.Add(mynode);


foreach (SPList myList in myWeb.Lists)
{
string listLink = "" + myList.Title + "(" + myList.Items.Count.ToString() + ")
";

mynode = new TreeNode(listLink, null, null, myList.DefaultViewUrl, "_self");

parentNode.ChildNodes.Add(mynode);

}

foreach (SPWeb childweb in myWeb.Webs)
{
Iterateotherwebs(childweb, parentNode);
}
tviewSiteStructure.CollapseAll();
}
}

}
void Iterateotherwebs(SPWeb web, TreeNode ParentNode)
{
TreeNode mynode = new TreeNode(web.Title, null, null, web.Url, "_self");
TreeNode parentNode = mynode;
tviewSiteStructure.Nodes.Add(mynode);

foreach (SPList myList in web.Lists)
{
string listLink = "" + myList.Title + "("+myList.Items.Count.ToString()+")
";

mynode = new TreeNode(listLink, null, null, myList.DefaultViewUrl, "_self");
parentNode.ChildNodes.Add(mynode);

}

foreach (SPWeb childweb in web.Webs)
{
Iterateotherwebs(childweb, parentNode);
}

}
}

}

No comments: