Thursday, May 23, 2013

Programmatically Creating SharePoint Lists, Be Careful With Column Names and Watch Out for the Trailing Zero

Recently I was working on a Feature that when activated would create a new list in the site.  I was creating the list and its columns via code, and had a line that looked something like this:

SPFieldText fldGuid = (SPFieldText)newList.Fields.CreateNewField(SPFieldType.Text.ToString(), Constants.FieldGuid);
newList.Fields.Add(fldGuid);
So here I'm creating a new Text field with the name of "GUID" and adding it to the list.  This works great in the code, the list is created and my column is there.  This can be easily confirmed by surfing to list and visually checking.

Now I populate some data in the list with a valid GUID and start to query the list using CAML.  And, presto.......nothing comes back!  Even if I used the same GUID hard coded nothing will return.  In these scenarios its time to open CAML Designer and make sure my query is correct.  Looking at the list in Designer, I see that the column name has a trailing zero (GUID0)!


What?!  After some head scratching I remember that SharePoint has a set of reserved names that you cannot use for your column names.  GUID is definitely one of those.

You can get a complete list of the reserved names here: Reference list for SharePoint internal field names.

So, the moral of the story here is keep in mind reserved column names when programmatically creating lists and columns in SharePoint.  As you can see in this example, SharePoint will not throw any errors, just modify the internal name for you!

Enjoy!

1 comment:

  1. hey

    Hope you like the caml Designer, but this version will no longer be supported... try the Caml Designer 2013 (also supports SP 2010) . :-)

    have a nice day
    kind regards
    andy

    ReplyDelete