Changing default view for ListViewWebPart programmatically.

Hi2all! Recently I faced with problem of changing default view for ListViewWebPart. My ListViewWebPart placed is on the meeting workspace site, on default.aspx page.I need to switch view programmatically to custom. Ok, at first glance not so hard. We must take instance of our webpart and set it property “ViewGuid” equal to custom view id in list, which is associated with webpart. Here is a peace of code:

var file = workspaceWeb.Files["default.aspx"];
var wpMngr = file.GetLimitedWebPartManager(PersonalizationScope.Shared);
var attendeeListViewWebPart = (ListViewWebPart)wpMngr.WebParts.Cast<WebPart>().FirstOrDefault(w => w.Title.Equals("Attendees"));
var list = workspaceWeb.Lists["Attendees"];
var view = list.Views["Attendees"];
attendeeListViewWebPart.ViewGuid = view.ID.ToString("B").ToUpper();
wpMngr.SaveChanges(attendeeListViewWebPart);

But it not works as expected. I get reference to SPLimitedWebPartManager, find my webpart and try to update ViewGuid, but every time I try to save changes I get error “The specified view is invalid”. Very strange behavior I suppose. I try to solve this issue about 8 hours and I find solution at last. May be it will be surprise for you, but every time when you add ListViewWebPart to a page, it internally creates hidden view in list. This hidden view belong to this webpart, it id generates by webpart and webpart set its own ViewGuid equal to this id. Let’s check it using SharePoint Manager 2010. I create test site collection from blank site and create links list named “dummy”. Let’s go to SharePoint Manager:

More...