Code Snippet – Programmatically Add the Web Part on the SharePoint Web Part Page

Since MOSS 2007 days (including SharePoint 2010), users and developers can create the web part pages. I am sure it’s been blogged several different places but if you have web parts already deployed on the site collection web part gallery and if you want to add the web part on the web part page programmatically, please use the following code snippet. If you want to add the Web Part to a Web Part page, you have to simply tell the Web Part manager in which zone to add the web part. This code snippet is mainly for my personal reference but feel free to use it.


class Program
{
    static void Main(string[] args)
    {
        SPSite spSite = new SPSite("http://sp2010vm/");
        foreach (SPWeb spWeb in spSite.AllWebs)
        {
            spWeb.AllowUnsafeUpdates = true;

            // Add the web part to the web part page
            SPFile page = spWeb.GetFile("SampleWebPartPages/SampleWebPartPage.aspx");
            using (SPLimitedWebPartManager lwpm = page.GetLimitedWebPartManager(PersonalizationScope.Shared))
            {
                try
                {
                    lwpm.AddWebPart(
                        new SiteOwnersNameSpaceName.SiteOwnersClassName()
                        {
                            Title = "Sites List Web Part",
                            AllowEdit = false,
                            AllowClose = false,
                            AllowHide = false,
                            AllowMinimize = false,
                            AllowConnect = false,
                            AllowZoneChange = false,
                            ChromeType = PartChromeType.None
                        },
                        "Left",
                        1);
                }
                finally
                {
                    if (lwpm.Web != null)
                    {
                        lwpm.Web.Dispose(); // SPLimitedWebPartManager.Web object Dispose() called manually
                    }
                }
            }

            spWeb.AllowUnsafeUpdates = false;
            spWeb.Dispose();
        }

        spSite.Dispose();

    }
}

Advertisements
This entry was posted in SP2010 Code Snippets. Bookmark the permalink.