SPList: add columns to the DefaultView

I came across some strange behavior of the Sharepoint Object Model (OM) when adding a new column (field) to the default view of an existing list.

Surprisingly (or not :) ) the following code snippet doesn’t seem to work:

list.DefaultView.ViewFields.Add(ACCOUNT);
list.DefaultView.Update();

But what you say if the following one is working:

SPView defaultView = list.DefaultView;
defaultView.ViewFields.Add(ACCOUNT);
defaultView.Update();

Let’s take a closer look in debugger to see what happens when running this code:

The first print-screen displays the current properties of the default view object:

SPList - add columns to the DefaultView 1

The following image display the properties of the defaultView object :

SPList - add columns to the DefaultView 2

Looks like the SPView defaultView = list.DefaultView code line makes a copy of the default view. The defaultView has different fields after this step:

SPList - add columns to the DefaultView 3

Update method seems to synchronize the information with the real view object (tried to see Update method with the reflactor but it is obfuscated):

SPList - add columns to the DefaultView 4

85 comments to SPList: add columns to the DefaultView

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Comment Spam Protection by WP-SpamFree