In this post we will see how to retrieve the items from multiple lists using SPSiteDataQuery in SharePoint 2013.
SPSiteDataQuery:
It is used to retrieve data from list or from all list in the site collection (i.e. used for cross-site and cross-list queries).
SPSiteDataQuery.Webs:
This property will be used to specify from where the data will be retrieved.
SPWeb.GetSiteData:
It is used to retrieve the data.
Sample Code to retreive the Items from the Tasks list
SPSiteDataQuery:
It is used to retrieve data from list or from all list in the site collection (i.e. used for cross-site and cross-list queries).
SPSiteDataQuery.Webs:
This property will be used to specify from where the data will be retrieved.
SPWeb.GetSiteData:
It is used to retrieve the data.
Sample Code to retreive the Items from the Tasks list
string siteUrl = SPContext.Current.Web.Url;
string username=string.Empty;
using (SPSite site = new SPSite(siteUrl ))
{
using (SPWeb web = site.RootWeb)
{
SPUser user = web.CurrentUser;
username = user.LoginName;
SPSiteDataQuery dataQuery = new SPSiteDataQuery();
//if it is set to SiteCollection, the query considers all Web sites that are in the same site collection as the current Web site.
dataQuery.Webs = "<Webs Scope=\"SiteCollection\">";
//if it set to Recursive the query considers only the current Web site and all subsites of the current Web site.
//dataQuery.Webs = "<Webs Scope=\"Recursive\">";
//107 Maps to the tasks list
dataQuery.Lists = "<Lists ServerTemplate=\"107\" />";
dataQuery.ViewFields = "<FieldRef Name=\"Title\" />" + "<FieldRef Name=\"AssignedTo\" />" + "<FieldRef Name=\"DueDate\" />";
string spQuery = "<Where><Eq><FieldRef Name=\"AssignedTo\"/><Value Type='User'>" + username + "</Value></Eq></Where>";
dataQuery.Query = spQuery;
DataTable dt = web.GetSiteData(dataQuery);
DataView dv = new DataView(dt);
gvResult.DataSource = dv;
gvResult.DataBind();
}
}