Accessing SPListItem.Fields Property

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.

5 thoughts on “Accessing SPListItem.Fields Property”

  1. i get the exact same exception, using the getfieldbyinternalname method. anything else i could try ?

  2. The same error is encountered for SPListItem[“ColName”] will throw the same argument exception if the column does not exist.can you please suggest a work around for this case as well?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.