Lars Nielsen's Discoveries

March 6, 2011

SharePoint Built In Fields

Filed under: Development,Good Practice,SharePoint — Lars Nielsen @ 6:19 pm
Tags: ,

Instead of using hard-coded strings for the names of the built in fields in SharePoint, you can use the object model to get the GUID of the field.  So instead of doing this:


SPListItem i;

// Get a list item into i

string moderationStatus = i["_ModerationStatus"] ;

You can do this:


SPListItem i;

// Get a list item into i

string moderationStatus = i[SPBuiltInFieldId._ModerationStatus] ;

This will get you a reference to the correct field using its GUID rather than its name.  The full list of built in fields is in the SPBuiltInFieldId documentation.  The SharePoint Kings blog also has an explanation of this class and also SPBuiltInContentTypeId.  There are a couple of problems with the fields to watch out for:

  • If you want to get the account who created an item, use the field SPBuiltInFieldId.Author not SPBuiltInFields.Created_x0020_By
  • If you want to get the account that last modified an item, use SPBuiltInFieldId.Editor not SPBuiltInFieldId.Modified_x0020_By

I’m not sure when SPBuiltInFields.Created_x0020_By would work but in my experience on a regular list, it’s always empty so I used SPBuiltInFieldId.Author instead.  So for example to get the account that created a list item as an SPUser object (so you can get the name or their email address) use code like this:


SPListItem item;

// Set the value of item somehow

SPFieldUser createdByField = (SPFieldUser)item.Fields[SPBuiltInFieldId.Author];

SPFieldUserValue createdByUserValue = (SPFieldUserValue) createdByField.GetFieldValue(item[SPBuiltInFieldId.Author].ToString());

SPUser user = createdByUserValue.User;

Advertisements

1 Comment »


RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: