Add field to SPList default view

jjczopek picture jjczopek · Aug 23, 2011 · Viewed 17.5k times · Source

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.

Answer

Dribbel picture Dribbel · Aug 23, 2011

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();