Get list of web part(s) on a page in SharePoint using Object Model

By Jatin Prajapati

How to get the list of all web parts added on the page using Object Model in SharePoint.

using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls.WebParts;
In SharePoint development sometimes we need to get other web part information like Title, GUID for a particular page. So, using ObjectModel and using SPWebPartManager object we can get all the web parts add on the WebPart page. Following code will show you how to accomplish this task.

using Microsoft.SharePoint;
using System.Reflection;
using System.Xml;
using System.Web.UI.WebControls;
using Microsoft.SharePoint.WebPartPages;

namespace GetPageWebPartsInfoWebPart
{
    [Guid("028a3d5f-5b9c-48ca-a4c3-68fa0433cdc9")]
    public class GetPageWebPartsInfoWebpart : Microsoft.SharePoint.WebPartPages.WebPart
    {
        private SPWeb _theWeb;

        public GetPageWebPartsInfoWebpart()
        {
            this.ExportMode = WebPartExportMode.All;        
            _theWeb = SPContext.Current.Web;
        }

         /// <summary>
        /// Create all your controls here for rendering.
        /// Try to avoid using the RenderWebPart() method.
        /// </summary>
        protected override void CreateChildControls()
        {
            try
            {
                 this.GetWebPartsOnThisPage();
             }
             catch (Exception ex)
            {
               HandleException(ex);
            }
        }

        private void GetWebPartsOnThisPage()
        {
            SPWebPartManager webPartManager = SPWebPartManager.GetCurrentWebPartManager(Page) as SPWebPartManager;
           Table tbl = new Table();
            tbl.Rows.Add(new TableRow());
            tbl.Rows[0].Cells.Add(new TableCell());
            tbl.Rows[0].Cells[0].Controls.Add(new LiteralControl("Web Parts on the page"));
            tbl.Rows[0].Cells[0].ColumnSpan = 2;
            for (int i = 0; i < webPartManager.WebParts.Count; i++)
            {
               TableRow row = new TableRow();
               TableCell cell = new TableCell();
                 row.Cells.Add(cell);
                 cell.Text = webPartManager.WebParts[i].Title;
               TableCell cell2 = new TableCell();
                 row.Cells.Add(cell2);
                 cell2.Text = webPartManager.WebParts[i].ID.TrimStart("g_".ToCharArray()); //g_ will come as prefix for GUID;
                 tbl.Rows.Add(row);
            }
            this.Controls.Add(tbl);
        }      
    }
}

Get list of web part(s) on a page in SharePoint using Object Model  (1162 Views)