Querying items in a SharePoint List

When querying a list in SharePoint, the SPList.GetItems method is a simple and relatively easy way to return a list of records from the SharePoint List (returned as a SPListItemCollection). This is implemented simply as follows:

using (SPWeb currentWeb = currentSite.OpenWeb(_RelativeWebUrl))
{
       SPList currentList = currentWeb.Lists[_ListName];  
       SPListItemCollection items = currentList.GetItems();
}

As you progress a bit, you will find that you won’t necessarily want to return all the items in a list. That’s when using the SPQuery object comes in real handy. Simply write the CAML query for the code that you wish to return, then pass the SPQuery object to the GetItems method. This should then return the exact subset of data that you were after. (

using (SPWeb currentWeb = currentSite.OpenWeb(_RelativeWebUrl))
{
       SPList currentList = currentWeb.Lists[_ListName];
       SPQuery query = new SPQuery();                    
       query.Query = String.Format("<Where><Eq><FieldRef Name=\"{0}\" /><Value Type=\"{1}\">{2}</Value></Eq></Where>",_InternalName, _Type,_Value);     
       SPListItemCollection items = currentList.GetItems(query);
}

HOWEVER, you must be careful that you write your CAML code correctly, or the method will return all records! This really surprised me and is a strange ‘feature’ one would think – I personally would have thought this should have returned NO records if it the query was incorrect. So basically if you find that every time you run a query there is a full record set returning, then check your CAML query…

For testing or writing your CAML queries, I would recommend downloading and trying out the U2U CAML Query Builder Рthis is a great little tool.

About these ads
This entry was posted in SharePoint. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s