Con-view-sed
Written on April 9, 2008 by Bryan
You might think this would be the correct way to add a field to a list default view programmatically:
string fieldInternalName = "MyField";
list.DefaultView.ViewFields.Add(fieldInternalName);
list.DefaultView.Update();
You’d be wrong.
This won’t work.
You might then try to update the list, or try to pass in the field itself to the Add method instead of the internal name. You might then try to do it with and without the Update method many times. Then you might search for code examples online where people are basically doing the same thing, only with a minor difference:
string fieldInternalName = "MyField";
SPView defaultView = list.DefaultView;
defaultView.ViewFields.Add(fieldInternalName);
defaultView.Update();
You might say to yourself "This is exactly the same thing I’m doing except I’m just using less code (and less memory)." Then you might decide you’ve tried everything else so why not just try this anyway? You will then replace your code with this version.
This will work.
Then you might open .NET Reflector and try to make some sense of why this works one way and not the other. You will not be able to. Then you close .NET Reflector feeling even more confused. Finally you will realize you just don’t understand SharePoint or .NET as well as you thought you did.

Leave a comment
You must be logged in to post a comment.