tags:

views:

192

answers:

1

Hi,

I'm customize the fields displayed in the Pages document library (the table displayed clicking site actions->all site content->pages).

It was suggested by someone who knows more about sharepoint than me that I should perhaps remove the fields which I didn't want from the default view programmatically on the activation of a feature, so I've written this code which feels like a very unelegant solution, and also does not work.

SPWeb web = properties.Feature.Parent as SPWeb;

        if (web != null)
        {
            SPList list = web.Lists["Pages"] as SPList;
            if (list != null)
            {
                foreach (SPField field in list.Fields)
                {
                    if (field.Title != "Type" &&
                        field.Title != "Name" &&
                        field.Title != "Modified" &&
                        field.Title != "Checked Out To" &&
                        field.Title != "Page Layout")
                    {
                        if (list.DefaultView.ViewFields.Exists(field.InternalName))
                        {
                            list.DefaultView.ViewFields.Delete(field);                                
                        }
                    }
                }

                list.DefaultView.Update();
            }
        }
    }

The code definately executed on activation of the feature so I'm obviously doing something wrong. I've searched for a solution to this so I apologise if I've missed something on google or this site which is blindingly obvious.

+2  A: 

This is because the changes to list.DefaultView.ViewFields are going out of scope. The collection is being refreshed from the database before the call to Update() is reached. Try:

if (list != null)
{
    SPView view = list.DefaultView;

    foreach (SPField field in list.Fields)
    {
     if (field.Title != "Type" &&
      ...
      field.Title != "Page Layout")
     {
      if (view.ViewFields.Exists(field.InternalName))
      {
       view.ViewFields.Delete(field);                                
      }
     }
    }

    view.Update();
}
Alex Angas