Класс SPSiteDataQuery

Представляет запрос, который может выполняться через несколько списков в нескольких веб-сайтов в одном семействе веб-сайта.

Иерархия наследования

System.Object
  Microsoft.SharePoint.SPSiteDataQuery

Пространство имен:  Microsoft.SharePoint
Сборка:  Microsoft.SharePoint (в Microsoft.SharePoint.dll)

Синтаксис

'Декларация
Public NotInheritable Class SPSiteDataQuery
'Применение
Dim instance As SPSiteDataQuery
public sealed class SPSiteDataQuery

Замечания

Экземпляр этого класса можно использовать для извлечения данных из выбранных списков или из всех списков в текущем семействе сайтов. Укажите область запроса с помощью свойства Webs . Укажите списки для участия в запросе, задав свойство Lists и полей для возврата путем установки свойства ViewFields . Выбор элемента управления данными и заказа с помощью свойства Query .

Чтобы выполнить запрос, передайте объект SPSiteDataQuery методу GetSiteData(SPSiteDataQuery) , которое возвращает объект DataTable , содержащий строк данных, представляющих результат запроса. Каждый объект DataRow в коллекции DataTable.Rows представляет один элемент, которая должна удовлетворять запрос. Каждый объект DataColumn в коллекции DataTable.Columns представляет поле, которое запрашивается в свойстве ViewFields , а имя столбца — это значение атрибута Name для этого поля. Кроме того в таблице данных содержит столбец с именем WebId, которая идентифицирует веб-сайт, содержащий каждого элемента, столбец с именем ListId, который определяет список, содержащий каждого элемента и столбец с именем ID, который определяет каждого элемента.

Примеры

Следующий пример является веб-часть, которая запрашивает всех списков, которые были созданы с контактами, в любом месте шаблон списка в коллекции веб-сайтов извлекает имена и фамилии каждого контакта и отображает, которые управляют сведения в GridView .

Note that if you compile the example code, you can deploy the Web Part simply by copying the compiled assembly to the bin directory of the Web application. If you choose that method of deployment, be sure your project includes a reference to Microsoft.SharePoint.Security.dll. Then add the Web Part to the SafeControls list in the web.config file and elevate the Web application's trust level to WSS_Medium. For more information, see Deploying Web Parts in Windows SharePoint Services and Securing Web Parts in Windows SharePoint Services.

Предупреждение

Значение перечисления для Contacts — 105.

Imports System
Imports System.Data
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports Microsoft.SharePoint

Public Class ContactViewer
   Inherits WebPart

   Private grid As GridView

   Protected Overrides Sub CreateChildControls()
      MyBase.CreateChildControls()

      ' Add an instance of the grid control.
      Me.grid = New GridView()
      Controls.Add(Me.grid)

   End Sub

   Protected Overrides Sub RenderContents(ByVal writer As System.Web.UI.HtmlTextWriter)

      Dim web As SPWeb = SPContext.Current.Web
      Dim query As SPSiteDataQuery = New SPSiteDataQuery()

      ' Ask for all lists created from the contacts template.
      query.Lists = "<Lists ServerTemplate='105' />"

      ' Get the Title (Last Name) and FirstName fields.
      query.ViewFields = "<FieldRef Name='Title' />" + _
                         "<FieldRef Name='FirstName' Nullable='TRUE' Type='Text'/>"
      ' Note that setting the Nullable attribute to TRUE
      ' causes an empty value to be returned for lists that
      ' do not include the FirstName column. The default is 
      ' to skip a list that does not include the column.

      ' Set the sort order.
      query.Query = "<OrderBy>" + _
                        "<FieldRef Name='Title' />" + _
                    "</OrderBy>"

      ' Query all Web sites in this site collection.
      query.Webs = "<Webs Scope='SiteCollection' />"

      Dim dt As DataTable = web.GetSiteData(query)
      Dim dv As DataView = New DataView(dt)

      ' Set up the field bindings.
      Dim boundField As BoundField = New BoundField()
      boundField.HeaderText = "Last Name"
      boundField.DataField = "Title"
      Me.grid.Columns.Add(boundField)

      boundField = New BoundField()
      boundField.HeaderText = "First Name"
      boundField.DataField = "FirstName"
      Me.grid.Columns.Add(boundField)

      Me.grid.AutoGenerateColumns = False
      Me.grid.DataSource = dv
      Me.grid.DataBind()

      Me.grid.AllowSorting = True
      Me.grid.HeaderStyle.Font.Bold = True

      Me.grid.RenderControl(writer)

   End Sub

End Class
using System;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;

namespace SampleWebParts
{
   public class ContactViewer : WebPart
   {
      private GridView grid;

      protected override void CreateChildControls()
      {
         base.CreateChildControls();

         // Add an instance of the grid control.
         this.grid = new GridView();
         this.Controls.Add(this.grid);
      }

      protected override void RenderContents(HtmlTextWriter writer)
      {
         SPWeb web = SPContext.Current.Web;
         SPSiteDataQuery query = new SPSiteDataQuery();

         //Ask for all lists created from the contacts template.
         query.Lists = "<Lists ServerTemplate=\"105\" />";

         // Get the Title (Last Name) and FirstName fields.
         query.ViewFields = "<FieldRef Name=\"Title\" />" +
                            "<FieldRef Name=\"FirstName\" Nullable=\"TRUE\" Type=\"Text\"/>";
        // Note that setting the Nullable attribute to TRUE
        // causes an empty value to be returned for lists that
        // do not include the FirstName column. The default is 
        // to skip a list that does not include the column.

         // Set the sort order.
         query.Query = "<OrderBy>" + 
                           "<FieldRef Name=\"Title\" />" + 
                       "</OrderBy>";

         // Query all Web sites in this site collection.
         query.Webs = "<Webs Scope=\"SiteCollection\" />";

         DataTable dt = web.GetSiteData(query);
         DataView dv = new DataView(dt);

         // Set up the field bindings.
         BoundField boundField = new BoundField();
         boundField.HeaderText = "Last Name";
         boundField.DataField = "Title";
         this.grid.Columns.Add(boundField);

         boundField = new BoundField();
         boundField.HeaderText = "First Name";
         boundField.DataField = "FirstName";
         this.grid.Columns.Add(boundField);

         this.grid.AutoGenerateColumns = false;
         this.grid.DataSource = dv;
         this.grid.DataBind();

         this.grid.AllowSorting = true;
         this.grid.HeaderStyle.Font.Bold = true;

         this.grid.RenderControl(writer);
      }
   }
}

Потокобезопасность

Любые общедоступные элементы static (Shared в Visual Basic) этого типа являются потокобезопасными. Не гарантируется, что любые элементы экземпляров потокобезопасны.

См. также

Справочные материалы

Элементы SPSiteDataQuery

Пространство имен Microsoft.SharePoint