The following article helped me a little bit:
However I found that when doing the same on publishing pages things become slightly trickier.
I have looked at 3 different things that we could do to the ListViewWebPart:
First for all of these operations we need to:
- get the web part manager,
- checkout the page and
- run with elevated permissions
- Allow Unsafe Updates
So the framework for our three functions is:
using (SPSite eSite = new SPSite(web.Url))
using (SPWeb eWeb = eSite.OpenWeb())
eWeb.AllowUnsafeUpdates = true;
SPFile page = eWeb.GetFile(“Pages/default.aspx”);
if (page != null)
SPLimitedWebPartManager WebPartManagerUpdate = page.GetLimitedWebPartManager(PersonalizationScope.Shared);
// Do all the important stuff
page.CheckIn(“Done something to the page”);
page.Publish(“Done something to the page”);
Note that the Checkout happens before I get the LimitedWebPartManager. Initially I did this the other way around. However this resulted in getting errors when you check the page back in. The system will complain that the page is already checked out by someone else. It looks like the GetLimitedWebPartManager call does an auto checkout when the page isn’t checked out.
So now that we have the framework for our 3 functions in place I’ll look at the specifics:
Delete a Web Part
XsltListViewWebPart docWebpart = null;
foreach (System.Web.UI.WebControls.WebParts.WebPart aWebpart in WebPartManagerUpdate.WebParts)
if (aWebpart.Title == WebPartTitle)
docWebpart = aWebpart as XsltListViewWebPart;
// Delete it
if (docWebpart != null)
// remove the Xslt web part
Update a Web Part
I have a list view web part on my page which currently shows document and I want to show only emails:
var emailListViewWebPart = (XsltListViewWebPart)WebPartManagerUpdate.WebParts.Cast().FirstOrDefault(w => w.Title.Equals("MyEmails"));
var eDocLib = eWeb.Lists.TryGetList("Documents");
var view = eDocLib.Views.Cast().FirstOrDefault(w => w.ID.ToString("B").Equals(emailListViewWebPart.ViewGuid, StringComparison.OrdinalIgnoreCase));
view.Query = "";
Add a Web Part
Now I’m adding a new Xslt Web part to page and setting the view.
XsltListViewWebPart newDocWebpart = new XsltListViewWebPart
Title = “All My Documents”,
ListName = docLib.ID.ToString(“B”).ToUpper(),
ListId = docLib.ID,
Visible = true
WebPartManagerUpdate.AddWebPart(newDocWebpart, “TopLeftRow”, 0);
var allDocView = docLib.Views[“All Documents”];
newDocWebpart.ViewGuid = allDocView.ID.ToString(“B”).ToUpper();
So what if I want to replace my web part or add and update. Do I just merge the code in this article?
No that isn’t going to work. I found that I had the check in my changes to the page. Then re-get the web part before I could find the updates.
So it is best to build the above three functions rather than doing multiple operations on the same web part.