Add field to SPList default view
Asked Answered
L

1

11

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.

Lucerne answered 23/8, 2011 at 11:35 Comment(0)
H
28

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();
Humanism answered 23/8, 2011 at 13:46 Comment(2)
No problem, I've struggled with this myself too.Humanism
Ugh kill me now SharePoint! Way to totally break the idea of properties.Haustorium

© 2022 - 2024 — McMap. All rights reserved.