Thursday, April 2, 2009

SPWeb Collection: List Sites / Webs

I had an opportunity recently to make a web part that is like a site map to the entire site collection no matter where it was dropped on the SharePoint site. I also made an option (not shown in code) that allows the "default starting site/web" to be overridden so that you can start from any site/web node and then show recursive webs from there.

Enough talk, here's the code:

using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebPartPages;
using Microsoft.SharePoint.Utilities;
using System.Data;

namespace JamesCurtis.SharePoint.Examples
{
public class SPWebCollectionExample : Microsoft.SharePoint.WebPartPages.WebPart
{
#region Constants

#endregion

#region Fields

Label lblDisplay = new Label();
Label lblError = new Label();
StringBuilder sb = new StringBuilder();

#endregion

#region Delagates

protected override void CreateChildControls()
{
try
{
base.CreateChildControls();

lblDisplay.Text = GetData(SPContext.Current.Site.Url);
this.Controls.Add(lblDisplay);
}
catch (Exception ex)
{
lblError.Text = ex.Message;
this.Controls.Add(lblError);
}
}

#endregion

#region Private Methods

protected string GetData(string site)
{
using (SPSite s = new SPSite(site))
{
SPWebCollection swc = s.AllWebs;
for (int i = 0; i < swc.Count - 1; i++)
{
sb.Append(SPEncode.HtmlEncode(swc[i].Url));
sb.Append("<br/>");
}
}
return sb.ToString();
}

#endregion

}
}

Happy Programming!