Getting field values of an SPListItem returned from an SPQuery – watch out!

Getting field values of an SPListItem returned from an SPQuery – watch out!

I have seen and read about this gotcha before but even so I still fell for it today and it took for a couple of hours to figure out so I’ve decided to blog about it.

If you are working with SharePoint items in code which you have returned using a CAML query then you should always populate the SPQuery instance’s ViewFields property. You must include in here all the fields for which you might need to get the value of later. Failure to do this will mean the returned SPListItem instances might not contain the data for certain fields and will throw an exception (usually ‘Value was not within the expected range’).

The ViewFields property is set like this

[code lang="plain"]

<fieldref name="Title" /><fieldref name="Created" /><fieldref name="ID" />

[/code]

You can then access a fields value on an SPListItem instance using the normal code:

[code lang="csharp"]

SPListItem item = list.GetItemById(1);

string Title = item["Title"].ToString();

[/code]

Hope this helps!!

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">