Question

How do I programmatically move a WebPart from one zone to another on a page?

I have multiple sites that I want to loop through each site and update the page.

Was it helpful?

Solution

Use the SPLimitedWebPartManager.MoveWebPart method:

string zoneId = "TopZone";           // ID of the WebPartZone control
string zoneIndex = 0;                // Location of web part within zone
string webPartTitle = "Sales Tips";  // Title of web part
string filename = "default.aspx";    // Filename relative to SPWeb object

using (SPLimitedWebPartManager webPartManager = 
    site.GetLimitedWebPartManager(filename, PersonalizationScope.Shared))
{
    try
    {
    	foreach (WebPart webPart in webPartManager.WebParts)
    	{
    		if (webPart.Title == webPartTitle)
    		{
    			webPartManager.MoveWebPart(webPart, zoneId, zoneIndex);
    			webPartManager.SaveChanges(webPart);
    			break;
    		}
    	}
    }
    finally
    {
    	webPartManager.Web.Dispose();
    }
}

OTHER TIPS

In addition to the answer from Alex, be careful when you iterate your site collections and sites. If you do this from for example a console application where you have to establish your own context, you will run out of memory very fast if you forget to dispose your SPSite and SPWeb objects while iterating (eg. sites.AllWebs).

read and understand the disposing guidelines on MSDN:Best Practices: Using Disposable Windows SharePoint Services Objects

Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top