Move a Web Part on a Page
This particular command was one that I didn't actually need but rather I needed a starting place for a couple other commands that I did need (to be documented) and moving a web part seemed a simple enough starting place for manipulating web parts. So this one was really just a template for my other commands but it works rather well and who knows, maybe someone will benefit from it. Moving a web part is actually quite simple - you just call the SPLimitedWebPartManager's MoveWebPart method passing in the web part to move, the zone ID to move to, and the zone index (position in the zone). And then you just call SaveChanges passing in the web part.
All the real work is in locating the web part to move which is a little trickier than it should be because the Title field is not unique but it's a lot more convenient for the user to use the title rather than the cryptic ID. The other thing is the the zone ID is a string and could theoretically be any value so the caller needs to know what values to provide (this is where the gl-enumpagewebparts command comes in handy along with retrieving the web parts ID if necessary). To facilitate getting the web part I created a couple helper methods, one gets the web part by ID the other by Title:
1: /// <summary>
July 16th, 2009 - 09:05
Gary,
Can this be used to put a webpart on a site if it is not there already?
thanks!
August 7th, 2009 - 17:29
Not this one – gl-setwebpartstate will though.
January 14th, 2010 - 10:34
Hi Gary,
When trying this command, I keep on getting this error message:
An ErrorWebPart cannot be saved during browse.
Any idea?
Thanks,
Frank
July 5th, 2010 - 17:51
Hi. I have a problem. When I execute the MoveWebPart method, the others webparts index of the same zone doesn’t update.
Somebody know why this happens?
Thanks!
August 17th, 2010 - 11:41
Hi Gary,
Love the SharePoint page!
I was wondering if you know of a way to output what is normally outputted when someone appends ?contents=1 on the querystring but for all users?
Currently I can replicate this but only for the current user and I’m interested in outputting the data for all usres.
string url = “http://spsite”;
using (SPSite site = new SPSite(url))
using (SPWeb page = site.OpenWeb())
{
//give relative path of the webpartpage
SPLimitedWebPartManager wm = page.GetLimitedWebPartManager(“default.aspx”, System.Web.UI.WebControls.WebParts.PersonalizationScope.User);
foreach (System.Web.UI.WebControls.WebParts.WebPart wp in wm.WebParts)
{
Response.Write(wp.Title.ToString() + “
“);
}
}
Thanks in advance!!
August 18th, 2010 - 00:10
I’ve not really looked into this so can’t say for sure but if you crack open that page and look at it in reflector you should be able to find what you need (that’s what I’d do to find the answer).
August 29th, 2010 - 03:53
Awesome post! I was searching for this for quite some time. Thanks for sharing the knowledge.