Monday, December 15, 2008

Changing fields by code - common oversight

I just helped someone on the OzMOss mailing list who had the following problem - he was trying to change a SPField object, but it was not getting updated, despite of no errors being thrown. Here is a sample of the code he was using:

Guid listID = web.Lists.Add("test", "", SPListTemplateType.PictureLibrary);
SPList list =web.Lists[listID];
SPField myField = list.Fields.GetFieldByInternalName("Title");
myField.Title = "TEST";
list.Update();
The problem with that code is a common oversight that developers who are new to the SharePoint object model usually make - the field object has to be updated. updating the list will have no effect, since the object that was modified was a column on the list, not a property of the list. The right code would be:
Guid listID = web.Lists.Add("test", "", SPListTemplateType.PictureLibrary);
SPList list =web.Lists[listID];
SPField myField = list.Fields.GetFieldByInternalName("Title");
myField.Title = "TEST";
myField.Update();

2 comments:

Wave Warior said...

I don't quite get it, maybe it's me but the code looks the same, maybe there is a slight difference I'm missing (which might be the case).

Cheers

Anonymous said...

The original code didn't call the update() method to update the change.

myField.Update();