Updating ListView Web Part Views in SharePoint 2007
Recently I got a question about a similar task that I had earlier last year and it involved a case where there were many (and I mean many) SharePoint 2007 sites and subsites containing webparts that had views showing certain SharePoint list information. However customer later realised that they needed the webpart views to contain the same view as the default view of the SharePoint list. So they asked if this can be done somehow automatically as a lot of time would be wasted updating each and every web part view manually (considering the amount of sites).Well since, like I said in the beginning, people in community started asking about the same thing I decided to share the piece of code that can do this for you.I suggest you write a code to iterate through every site, in my example below I’m just opening a particular site on my VM.
SPWeb web = new SPSite("http://starscream/").OpenWeb();
SPLimitedWebPartManager wm = web.GetLimitedWebPartManager("default.aspx", System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared); // If you have Publishing enabled I suggest you replace “default.aspx” with “Pages/Default.aspx” or whatever your default publishing page is, if this varies between different sites you should check before declaring a SPLimitedWebPartManager for example: web.GetFile("default.aspx").Exists
SPList list = web.Lists["Some Document Library"];
foreach (System.Web.UI.WebControls.WebParts.WebPart webPart in wm.WebParts)
{
if (webPart.GetType().Name == "ListViewWebPart" && webPart.Title == "Some Document Library")
{
ListViewWebPart myWebPart = (ListViewWebPart)webPart;
SPView doclibview = list.Views["All Documents"]; //actual view
Guid guid = new Guid(myWebPart.ViewGuid);
SPView webPartView = list.Views[guid];
webPartView.ViewFields.DeleteAll(); // deleting the existing view fields for adding new one
foreach (string strField in doclibview.ViewFields)
{
webPartView.ViewFields.Add(strField);
}
webPartView.Query = doclibview.Query;
webPartView.RowLimit = doclibview.RowLimit;
webPartView.ViewEmpty = doclibview.ViewEmpty;
webPartView.ViewFooter = doclibview.ViewFooter;
webPartView.ViewHeader = doclibview.ViewHeader;
webPartView.Scope = doclibview.Scope;
webPartView.GroupByFooter = doclibview.GroupByFooter;
webPartView.GroupByHeader = doclibview.GroupByHeader;
webPartView.Update();
myWebPart.ViewGuid = webPartView.ID.ToString("B").ToUpper();
myWebPart.Visible = true;
myWebPart.Title = "Some title";// you can change the title or leave it as it was before
wm.SaveChanges(myWebPart);
web.Update();
}
}