Cross Site List Query using SPSiteDataQuery in SharePoint 2010


In this article I am giving you an introduction on SPSiteDataQuery class. Most of the developers are naive about this class definitely this will give an introduction on the class. This will be beneficial if you want to Query multiple lists or want to read data from all the lists in a site collection.

We can use this class to retrieve data from selected lists or from all the lists in the current site collection. We have to set the following before we start.
  • Specify the scope of the query by setting the Webs property (Site collection, site etc). 
  • Specify the lists to participate in the query by setting the Lists property 
  • Specify the fields to return by setting the View Fields property. 
  • We have to Control data selection and order by setting the Query property.
In the below example I am using a site collection containing two task list. I am using SPSiteDataQuery to retrieve data from this entire task list.

Before starting make sure you have more than one Task list in the site collection. In my case I have created two

Task List 1

1.gif
 
Task List 2

2.gif
 
You have to create a visual web part for the next section. I already have an article on how to work with visual web part. If you want to know more details please click on the below link.


In the code you have to change the Template ID .I am using task list that's why I am using template ID as 107.I have set the Scope to Site collection level.

3.gif