Wednesday, February 16, 2011

CAML Query SPQuery Object and Where Clause

To fetch data/item (SPListItem ) from SharePoint List (SPList) we have to use CAML with SPQuery class.
We have already discussed CAML in our last post, now we will look at SPQuery class and Where Clause in a bit of detail in this post.

SPQuery Class is used to hold query, attributes, fields and other important properties.
To fetch data from list, we need to call GetItems function of SPList class.

Here is how it should be done.

SPList list = web.Lists["List Name"];
SPQuery query = new SPQuery();
query.Query = "<Where><Eq><FieldRef Name='Title'/><Value Type='Text'>Hello World</Value></Eq></Where>";

SPListItemCollection itemsCollection = list.GetItems(query);
GetItems of SPList class has 3 overloaded methods which takes SPQuery, SPList as arguments.
As SPListItemCollection is a collection which has SPListItem type items, we can access any item by either having a foreach loop or directly accessing an item by passing index.


No comments: