September 18, 2011

One Issue with Web.Fields.Add in SharePoint 2010

I was trying to add a field, and for the heck of it, I decided to start with a field name that has spaces in it:
string benefitsLongDesc = web.Fields.Add("Benefits Long Description", SPFieldType.Note, false);

SPField benefitsLongDescField = web.Fields[benefitsLongDesc];
benefitsLongDescField.Title = "Long Description";
benefitsLongDescField.Group = "Human Resources";

I was surprised that code line 4 failed to resolve field, even when I’m returning the internal field name from code line 1.

To resolve this, you have a couple of options:
  1. Don’t use spaces in the Display Name in code line 1, which is preferred as you don’t want your field internal name to contain spaces that get converted to _x0020_ and make your life miserable trying to remember to add those characters every time you want to call the field.
  2. In code line 3, instead of getting the field from web.Fields directly, use the following:
SPField benefitsLongDescField = web.Fields.GetFieldByInternalName(benefitsLongDesc);
Happy coding!

No comments:

Post a Comment