SharePoint 2013 – The specified view is invalid in call to LimitedWebPartManager.AddWebPart

Adding a webpart

Today I tried to add a web part to a page using the following code:

[code lang=text]
ListViewWebPart webpart = new ListViewWebPart();
webpart.Title = "Matter Emails";
webpart.ListName = item.ListItems.List.ID.ToString("B").ToUpper();
webpart.ViewGuid = item.ListItems.List.Views["All Emails"].ID.ToString();
webpart.Visible = true;
WebPartManager.AddWebPart(webpart, "TopLeftRow", 1);
WebPartManager.SaveChanges(webpart);
[/code]

This gave me a “The specified view is invalid” Exception on the AddWebPart call.

Your Solution

Then I moved the following line:

[code lang=text]
webpart.ViewGuid = item.ListItems.List.Views["All Emails"].ID.ToString();
[/code]

resulting in

[code lang=text]
ListViewWebPart webpart = new ListViewWebPart();
webpart.Title = "Matter Emails";
webpart.ListName = item.ListItems.List.ID.ToString("B").ToUpper();
webpart.Visible = true;
WebPartManager.AddWebPart(webpart, "TopLeftRow", 1);
<strong>webpart.ViewGuid = item.ListItems.List.Views["All Emails"].ID.ToString();</strong>
WebPartManager.SaveChanges(webpart);
[/code]

and the web part was added to the page with the correct view.

Advertisements

One thought on “SharePoint 2013 – The specified view is invalid in call to LimitedWebPartManager.AddWebPart

  1. Thanks, this was super helpful. SP makes me nervous sometimes… the same code that was working in MOSS2007 does not working in SP2016, because of the ordering within the code!

Leave a Reply

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

%d bloggers like this: