Programmatically Working with ListViewWebPart using Non-Default View (GetUncustomizedViewByBaseViewId)
If you add an Announcement web part to page from the web part gallery you get a nice view of the list which shows 5 items, shows (More Announcements…) link and “Add a new Announcement” link
This is exactly what I needed for one of my web part but my requirement was to add the web part to page from a feature programmatically and not using the UI.
After looking around for a while in MSDN and searching most of the examples showed how to set the properties of the ListViewWebPart programmatically but all of the examples used the Default View of the list as shown below (The default view is the view which you get by default on AllItems.aspx).
<br /> SPList list = web.Lists["Announcement"];<br /> ListViewWebPart webPart = new ListViewWebPart();<br /> webPart.Title = "Announcements";<br /> webPart.ViewGuid = list.DefaultView.ID.ToString("B").ToUpper();<br />
If you look at the Schema file for the list, the View with BaseViewID of 0 is the one which has the HTML to render the view in the ListViewWebPart
<View BaseViewID=”0″ FreeForm=”TRUE” Type=”HTML”>
So First thing that came to my mind was to iterate though the Views collection of SPList object and look for a view with BaseViewID of zero, but to my surprise it was not there in the collection OOPSSS! But If I add the Announcement web part using the UI and than search the Views collection of SPList object for BaseViewID of Zero than the View is found in the collection. So the moral of the story is SharePoint is doing some thing to customize the view and add it to the Views collection.
Now how do you do the same programmatically? Luckily I did not try very hard and found a method called GetUncustomizedViewByBaseViewId on the SPList object and that was it, here is the code snippet:
<br /> SPList list = web.Lists["Announcement"];<br /> ListViewWebPart webPart = new ListViewWebPart();<br /> webPart.Title = "Announcements";<br /> webPart.ListName = list.ID.ToString("B").ToUpper();<br /> SPView view = list.GetUncustomizedViewByBaseViewId(0);<br /> webPart.ListViewXml = view.HtmlSchemaXml;<br />
Few things though:
- You cannot use ViewGuid property of ListViewWebPart as ID of the View returned by GetUncustomizedViewByBaseViewId will be empty instead use ListViewXml property of ListViewWebPart and assign View’s HtmlSchemaXml property to it
- If your List is in a different SPWeb than the page on which you are adding ListViewWebPart than use WebId property of ListViewWebPart to point it to the ID of SPWeb which contains the List