My Sub Sites Web Part…


One web part that i think is missing in the out of the box parts is one that allows you to show the sub-sites of a site.  There are a couple out there already ... but i had the need to only show sub-sites that the user had access to. 


Anyway ... here is the code:


 [DefaultProperty("Text"),
  ToolboxData("<{0}:MySubSitesWebPart runat=server></{0}:MySubSitesWebPart>"),
  XmlRoot(Namespace="MySubSites")]
 public class MySubSitesWebPart : Microsoft.SharePoint.WebPartPages.WebPart
 {
  private const string defaultText = "";
  private string text=defaultText;


  private string title = "My Sub Sites";


  [Browsable(true),Category("Miscellaneous"),
   DefaultValue(defaultText),
   WebPartStorage(Storage.Personal),
   FriendlyName("Text"),Description("Text Property")]
  public string Text
  {
   get
   {


    StringBuilder builder = new StringBuilder();


    text = "";


    SPWeb currentSite = SPControl.GetContextWeb(Context);


    SPWebCollection subSites = currentSite.GetSubwebsForCurrentUser();
    
    builder.Append(@"<table border='0' width='100%'>");
 
    foreach(SPWeb site in subSites)
    {
     builder.Append("<tr><td class='ms-underlineback'>");
     builder.Append("<a href='");
     builder.Append(site.Url);
     builder.Append("' style='cursor:hand' title=''>");
     builder.Append(SPEncode.HtmlEncode(site.Title));
     builder.Append(@"</a></td></tr>");
    }


    builder.Append(@"</table>");


    return builder.ToString();
   }


   set
   {
    text = value;
   }
  }
  
  
  /// <summary> 
  /// Render this Web Part to the output parameter specified.
  /// </summary>
  /// <param name="output"> The HTML writer to write out to </param>
  protected override void RenderWebPart(HtmlTextWriter output)
  {
   output.Write(Text);
  }
 }

Comments (5)
  1. Bruce Barton says:

    CJ, can you tell me how to add this to my sites next time you are visiting? I will try and remind you.

    Cheers,

  2. miglena says:

    Very nice blog. It is very helpful. http://www.bignews.com

  3. Nice tip – glad to see the share; interesting to use the Property to create the actual output string.

Comments are closed.

Skip to main content