SharePoint 2013 – Remove, Add and Update List View Web Parts on publishing pages programmatically

Changing Default Views

Sergei Sergeev’s post about changing default views helped a bit hereHowever 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:
  • Delete
  • Add
  • Update

The basic steps

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:SPSecurity.RunWithElevatedPrivileges(delegate {

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) {

try {

page.CheckOut(); 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”);

}

catch

{

//Report Error

}

}

}

}

}); ; 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 WebPartManagerUpdate.DeleteWebPart(docWebpart);

}

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.ViewFields.Add("EmailFrom"); view.ViewFields.Add("EmailCc"); view.ViewFields.Add("EmailTo"); view.Query = ""; view.Update(); WebPartManagerUpdate.SaveChanges(emailListViewWebPart); 

 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); WebPartManagerUpdate.SaveChanges(newDocWebpart); var allDocView = docLib.Views[“All Documents”]; newDocWebpart.ViewGuid = allDocView.ID.ToString(“B”).ToUpper(); WebPartManagerUpdate.SaveChanges(newDocWebpart);

Bonus bits

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.

Frequently asked questions

Why does the example check out the page before obtaining its web-part manager?

Obtaining the manager first appeared to cause an automatic checkout and later check-in conflicts, so the article reverses that order.

How does it identify the view belonging to an existing list-view web part?

It matches the web part’s ViewGuid to a view in the document library, then updates the view and saves the web-part changes.

Can several add and update operations simply be merged?

The author found that changes needed to be checked in and the web part retrieved again before later operations saw them, so recommends separate functions.

What platform is this server-side code intended for?

It is a SharePoint 2013 publishing-page example using SPSite, SPWeb, elevated privileges and the limited web-part manager, not client-side SharePoint Online code.

Is your business still running on paper trails, sprawling Excel files, or ageing Access databases? There's a better way — and I can show you exactly what it looks like. I'm the Technical Director of Vantage 365, a Microsoft solutions consultancy working with clients across the UK, the Netherlands, and worldwide. For over 30 years I've been turning messy, manual business processes into clean, automated systems that save time, reduce errors, and give teams the visibility they need to make better decisions. SharePains is not just any blog run by a Microsoft MVP. Have you ever used Try-Catch in Power Automate? The original post about Try-Catch in Power Automate can still be found on this site, https://sharepains.com/2018/02/07/try-catch-finally-in-power-automate-flow/ Or have you ever used the Pieter’s method to avoid variables and speed up your flows? https://sharepains.com/2020/03/11/pieters-method-for-advanced-in-flows/ You can contact me using contact@sharepains.com

Related Posts

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

×