I was working on a feature stapler to add a list view on the landing page. I simply created an instance of the ListViewWebPart class, set the ListID, ViewGuid and the WebID and added the web part to the page. Great, I saw the web part on the page. But then, I realized that the web part was not rendering the view I had set.


Searching online, I found numerous articles describing how a ListViewWebPart works. To summarize, ListViewWebPart creates a hidden view and uses that view to render. So, even if you set the view while instantiating the web part, it does not use that view.

The solution for this was pretty simple, all I did was use the XSLTListViewWebPart instead of the ListViewWebPart and it used the view that I set. Here is a snippet of code that returns a XSLTListViewWebPart.

public static XsltListViewWebPart GetListWebPartWithViewFor(SPList list, string webPartTitle,string viewName)
XsltListViewWebPart lstWp = new XsltListViewWebPart();
SPView view = list.Views[viewName];
if (view != null)
lstWp.ViewGuid = view.ID.ToString();
lstWp.ViewGuid = list.DefaultView.ID.ToString();
lstWp.ListId = list.ID;
lstWp.WebId = list.ParentWeb.ID;
lstWp.Title = webPartTitle;
lstWp.ChromeType = System.Web.UI.WebControls.WebParts.PartChromeType.TitleOnly;

return lstWp;