Saturday, December 26, 2009

How to select the specific "Columns/Fields" from a Sharepoint List?

Introduction:

    We can retrieve specific set of data from Sharepoint site by using CAML Query and SPQuery Object.

What is the use SPQuery Object?

    SPQuery object help to filter the data from Sharepoint List. For filter purpose we can use CAML Query.

What is CAML?

    Collaborative Application Markup Language (CAML) is the XML-based language that  Microsoft uses to build and customize SharePoint sites. CAML queries allow you to dynamically find and display SharePoint items based on various criteria.

There are two main parts to a CAML query statement:
   
  • Conditions ( Where Clause ).
  • Sort (Order by).

CAML Query syntax.

    The root element is Query. Within the Query element two other elements are possible but not required. The OrderBy element and the Where element.

Ex :

 
   
     Books  
   
 
 
   
 

    Default Ordering is Ascending only, For Descending we need to the property "Ascending='False' ".

 How to select the specific "Columns/Fields"?

    By the help of "SPQuery.ViewFields" Property we can achieve this goal.
The ViewFields property allows you to specify which fields to return in a query on a list.
The ViewFields property contains a string that corresponds to the inner XML of the ViewFields element in CAML

ViewFields Example:


       
       
       
 


Note :

    If we want our query to return empty columns, We have to add Nullable='TRUE' to the viewfields

For Example



If we didn't add the Nullable attribute, while accessing the results of the query like this:

oItems["AssignedTo"] 

will give an Exception.

Sample Code Block

using (SPWeb oWebsite = SPContext.Current.Site.AllWebs[""])
{
    SPList oList = oWebsite.Lists[""];

    SPQuery oQuery = new SPQuery();

    // Selection Condition.
    oQuery.Query = "Books   ";

    // Seleted Fields
    oQuery.ViewFields = "" +
     "";

    // Retrieving Data from the List.
    SPListItemCollection oItems = oList.GetItems(oQuery);

    foreach (SPListItem oItem in oItems)
    {
        Response.Write(SPEncode.HtmlEncode(oItem.Xml));
    }
}

Thank You

1 comment:

Anonymous said...

This is terrible. Where is ViewFields in Caml??