I needed to change the list view of a web part that had already been deployed to 1700 site collections programmatically. Thanks to theses posts:
http://social.msdn.microsoft.com/Forums/en-US/sharepointdevelopment/thre…
and
http://community.zevenseas.com/Blogs/Robin/archive/2008/11/16/creating-a…
I came up with a solution:
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite spSiteTest = new SPSite(sURL))
{
using (SPWeb spWebTest = spSiteTest.OpenWeb())
{
SPFile targetPage = spWebTest.GetFile(“Pages/MyPage.aspx”);
SPLimitedWebPartManager webpartManager = null;
webpartManager = targetPage.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);
SPList documentLibrary = spWebTest.Lists[“Tasks”];
for (int k = 0; k < webpartManager.WebParts.Count; k++)
{
//get reference to webpart
//check webpart Title to find webpart which is to be removed
if (webpartManager.WebParts[k].Title.ToUpper() == “MY TASKS”)
{
SPList list = documentLibrary;
ListViewWebPart lvwp = (ListViewWebPart)webpartManager.WebParts[k];
SPView view = list.Views[new Guid(lvwp.ViewGuid)];
view.ViewFields.Delete(“AssignedTo”);
view.ViewFields.Add(“DueDate”);
view.Update();
//update spWeb object
spWebTest.Update();
}
}
}
}
});
}
catch (Exception ex)
{
TextFileWriter(ex.ToString());
}
I also learned that web parts of lists reference a hidden view–so just changing teh default view won’t affect your page that is displaying the list in a web part.