Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

How do I programmatically move a web part from one zone to another on a page? I have multiple sites that I want to loop through each site and update the page.

share|improve this question
add comment

2 Answers 2

up vote 7 down vote accepted

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();
    }
}
share|improve this answer
    
Alex, First of all, thank you for all your responses on the SO sites. Don't know how you have time to always answer so thoroughly. Second, when I call .SaveChanges and two web parts point to the same list, the titles are erased and say 'Link[1]' and 'Link[2]'. Any experience with this? I know this should be its own question but in case others come across this question, they may also see this. –  trgraglia Dec 22 '11 at 14:13
    
Alex. I wanted to move a personalized webpart to a different zone. I mean the user should be able to move the webpart in personalized view.. I used PersonalizationScope.User but some how the changes are not getting saved. –  user7672 Apr 2 '12 at 22:53
add comment

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: http://msdn.microsoft.com/en-us/library/aa973248.aspx

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.