Code Snippet – Programmatically Modify the Properties of the SharePoint Web Parts

Here is the quick code snippet to update the web part properties on the SharePoint 2007/2010 Web Part Pages and SharePoint 2010 Wiki Pages. Please note that adding web parts on the web part pages and wiki pages has different process but updating web part properties has similar process.

In the following code snippet, we are looping through all the webs in the site collection and update the “Shared Documents” web part title to the “Project Documents” on the Projects site home page. Please note that we are looping through the page web parts using the SPLimitedWebPartManager and use the web part manager’s SaveChanges method to apply the changes made to the web parts.

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

                    SPFile wikiFile = spWeb.GetFile("SitePages/Home.aspx");
                    using (SPLimitedWebPartManager wpm = wikiFile.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared))
                    {
                        try
                        {
                            foreach (System.Web.UI.WebControls.WebParts.WebPart wp in wpm.WebParts)
                            {
                                if (wp.Title == "Shared Documents")
                                {
                                    wp.Title = "Project Documents";
                                    wpm.SaveChanges(wp);
                                }
                            }
                        }
                        catch
                        {
                            if (wpm.Web != null)
                            {
                                wpm.Web.Dispose();
                            }
                        }
                    }

                    spWeb.AllowUnsafeUpdates = false;
                }
            }
        }
    }
}

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