Changing the web part list view in SharePoint

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.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s