Getting selected columns from a sharepoint list using SPQuery.ViewFields

 

Sometimes there is a need to query data pertaining to only specified columns from a sharepoint list.

Let's say I have a list "Employee" with columns - Name, ID, Age, Sex, Address, SSN etc. and I just want to retrieve data corresponding to columns Name & SSN for Employee with ID = 9 .

Syntactically, it can be accomplished as below -

// Code starts here

SPListItemCollection itemCol = null;

SPSite site = new SPSite("site url");
SPWeb web = site.OpenWeb();

SPList objList = web.Lists["listName"];
SPQuery qry = new SPQuery();
qry.Query = "<Where><Eq><FieldRef Name='ID' /><Value Type='Text'>"9"</Value></Eq></Where>";
qry.ViewFields = <FieldRef Name='Name'/><FieldRef Name='SSN'/>

itemCol = objList.GetItems(qry);

// Code ends here

Comments

  • Anonymous
    March 14, 2011
    how can i get to 100 rows  Name & SSN ?

  • Anonymous
    May 04, 2011
    The comment has been removed