How to get a List of Web Parts on a Page

Recently I got a question from a student how to get a list of all the web parts (in code) that are displayed on a specific SharePoint Web Part Page. This could be useful if you would like to close all the web parts at once, add web parts programmatically etc. By using the SharePoint object model this is pretty easy, especially if you want to retrieve that list with code running in a web part. The WebPartManager property of the WebPart base class, gives you access to a collection of all the WebPartZones available on the page. Once you've got the zones, you can get the web part instances by using the WebParts property. The following web part code will display a small list of all the web parts found on the page, including the name of the web part class and the web parts zone.

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

namespace WebPartLister
{
  public class WebPartLister : System.Web.UI.WebControls.WebParts.WebPart
  {
    BulletedList list;

    protected override void CreateChildControls()
    {
      list = new BulletedList();
      WebPartZoneCollection zones = this.WebPartManager.Zones;
      foreach (WebPartZone zone in zones)
      {
        WebPartCollection webparts = zone.WebParts;
        foreach (WebPart webpart in webparts)
        {
          list.Items.Add(
          string.Format("{0} ({1}), {2}",
            webpart.Title, webpart.GetType().Name,
            zone.DisplayTitle));
        }
      }
      this.Controls.Add(list);
    }

    protected override void Render(HtmlTextWriter writer)
    {
      EnsureChildControls();
      list.RenderControl(writer);
    }
  }
}

 

Technorati tags: ,

9 Comments

Comments have been disabled for this content.