Thursday, April 9, 2009

Using SPQuery with Views for dynamically controlling fields

Scenario:
For one of the webpart we wanted to get data from a list but client wanted to dynamically decide the columns displayed.

Solution:
Using SPQuery and SPView we can dynamically control fields.

Code:

using (SPWeb oWebsite = SPContext.Current.Site.AllWebs["Site_Name"])
{
SPList oList = oWebsite.Lists["DocLib_Name"];
SPView oView = oList.Views["View_Name"];

SPQuery oQuery = new SPQuery(oView);
oQuery.ViewAttributes = "Scope=\"Recursive\"";
SPListItemCollection collListItemsAvailable =
oList.GetItems(oQuery);

foreach (SPListItem oListItemAvailable in collListItemsAvailable)
{
Response.Write(SPEncode.HtmlEncode(oListItemAvailable["Name"]));
}
}

0 comments: