Add field to SPList default view

17,510

It won't work due to the fact that list.view[0] returns a new SPView on every call; see here. In your case you call update() on a new instance.

To make it work, store the view in a variable and add the field to that view. (Example is for default view, but list.View[0] should also work)

SPView view = list.DefaultView;
view.ViewFields.Add("Foo");
view.Update();
Share:
17,510
jjczopek
Author by

jjczopek

Updated on June 15, 2022

Comments

  • jjczopek
    jjczopek almost 2 years

    I've created an SPList instance with some custom fields. But When I'm viewing this list in sharepoint (default view), only Title column shows up. How can I add my columns to default view of my newly created list?

    I tried:

    list.Fields.Add("Foo", SPFieldType.Text, true):
    list.View[0].ViewFields.Add("Foo");
    list.View[0].Update();
    list.Update();
    

    But doesnt work.

  • Dribbel
    Dribbel over 12 years
    No problem, I've struggled with this myself too.
  • Nacht
    Nacht about 10 years
    Ugh kill me now SharePoint! Way to totally break the idea of properties.