Accessing SPListItem.Fields Property
September 08, 2008
An annoying “design bug” that happened to me today.
SPListItem item = …(get a valid SPListItem)…
SPField fieldDef = item.Fields[“FieldInternalName”];
raises a ArgumentException: “Value does not fall within the expected range” error. The property indexer does not accept internal names (StaticName property of the field) as valid index.
If you access the Fields property with the field’s display name, which was localized in my case, then it works well. However, as localization was a must, I couldn’t rely on the display name to be the same in all deployments.
THE WORKAROUND
Luckily, there’s a method in SPFieldCollection class called GetFieldByInternalName. Just substitute
item.Fields[“FieldInternalName”];
with
item.Fields.GetFieldByInternalName(“FieldInternalName”);
and the error is gone.