Thursday, July 7, 2011

How to delete a field from a list view in SharePoint 2010

In my previous post Add a field to a list view in SharePoint 2010 I talked about how to add a field to a list view. Today we’ll look how to remove a field from a list view.

Just like adding, you can do this by selecting the modify view button and deselecting the field that you want to delete from the current view.

Here’s how it’s done via code.

public static void RemoveFieldFromListView(string webUrl, string fieldStaticName, string listName)
{
using (SPSite site = new SPSite(webUrl))
{
using (SPWeb web = site.OpenWeb())
{                  
SPList list = null;
bool contains = false;
//This block will validate whether the given list is exists at the given web.
try
{
list = web.Lists[listName];
contains = true;
}
catch (Exception ex)
{
//Do your custom exceptions handling here.
}
if (contains)
{
try
{
web.AllowUnsafeUpdates = true;
SPField field = web.Lists[listName].Fields.TryGetFieldByStaticName(fieldStaticName) as SPField;// get the field using the static name of the field.
SPView view = list.DefaultView;/ get the default view.
if (view.ViewFields.Exists(field.StaticName)) // field is already in the view.
{
view.ViewFields.Delete(field); // delete the field from the view.
view.Update();// update the view
list.Update();// update the list
web.Update();// update the web
}
}
catch (Exception ex)
{
//Do your custom exceptions handling here.
}
finally
{
web.AllowUnsafeUpdates = false;
}
}                   
}
}
}

No comments:

Post a Comment