Adding a webpart
Today I tried to add a web part to a page using the following code: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);
This gave me a “The specified view is invalid” Exception on the AddWebPart call.The specified view is invalid in call to LimitedWebPartManager.AddWebPart
Your Solution
Then I moved the following line:webpart.ViewGuid = item.ListItems.List.Views["All Emails"].ID.ToString();resulting in
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);
webpart.ViewGuid = item.ListItems.List.Views["All Emails"].ID.ToString();
WebPartManager.SaveChanges(webpart);
and the web part was added to the page with the correct view.Frequently asked questions
When did the invalid view error occur?
It occurred when AddWebPart was called after setting ViewGuid on the new list-view web part.
What sequence worked in the example?
The author added the web part first, then set ViewGuid and saved the changes.

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!