Share via


SPDataSource Class

Represents Windows SharePoint Services data to data-bound controls.

Inheritance Hierarchy

System.Object
  System.Web.UI.Control
    System.Web.UI.DataSourceControl
      Microsoft.SharePoint.WebControls.SPDataSource

Namespace:  Microsoft.SharePoint.WebControls
Assembly:  Microsoft.SharePoint (in Microsoft.SharePoint.dll)

Syntax

<ProxyDesignerAttribute("Microsoft.Web.Design.Remote.FpDataSourceProxyDesigner, Microsoft.Web.Design.Client, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c")> _
<SharePointPermissionAttribute(SecurityAction.LinkDemand, ObjectModel := True)> _
<AspNetHostingPermissionAttribute(SecurityAction.LinkDemand, Level := AspNetHostingPermissionLevel.Minimal)> _
<SharePointPermissionAttribute(SecurityAction.InheritanceDemand, ObjectModel := True)> _
<AspNetHostingPermissionAttribute(SecurityAction.InheritanceDemand, Level := AspNetHostingPermissionLevel.Minimal)> _
Public Class SPDataSource _
    Inherits DataSourceControl _
    Implements ICloneable

Dim instance As SPDataSource
[ProxyDesignerAttribute("Microsoft.Web.Design.Remote.FpDataSourceProxyDesigner, Microsoft.Web.Design.Client, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c")]
[SharePointPermissionAttribute(SecurityAction.LinkDemand, ObjectModel = true)]
[AspNetHostingPermissionAttribute(SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
[SharePointPermissionAttribute(SecurityAction.InheritanceDemand, ObjectModel = true)]
[AspNetHostingPermissionAttribute(SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
public class SPDataSource : DataSourceControl, 
    ICloneable

Remarks

The SPDataSource data source control represents Windows SharePoint Services data to data-bound controls. You can use the control in conjunction with a data-bound control to retrieve data from lists, list items, and Web sites and to display, edit, and modify data with little or no code. For example, the following markup shows part of an ASP.NET page where the control is configured to retrieve data from a list.

<SharePoint:SPDataSource ID="SPDataSource1" 
    DataSourceMode="List"
    UseInternalName="true" 
    SelectCommand="<View></View>">
    <SelectParameters>
        <asp:Parameter Name="WebUrl" DefaultValue="/subsite/" />
        <asp:Parameter Name="ListName" DefaultValue="Contacts" />
    </SelectParameters>
</SharePoint:SPDataSource>

Key parts of the markup set the following properties of the control:

  • DataSourceMode property.

    This property specifies the data retrieval mode—that is, the type of Windows SharePoint Services data to query. In the example, the DataSourceMode property is set to List. Other valid modes are ListItem, CrossList, ListOfLists, and Webs. For information about these modes, see the SPDataSourceMode enumeration.

  • SelectCommand property.

    This property accepts a query in the form of a Collaborative Application Markup Language (CAML) fragment to specify such things as filtering, sort order, and the set of fields to return. The example markup does not specify a query, so the SPDataSource control returns all fields and all items.

  • SelectParameters property.

    This property returns a collection of parameters for use with the SelectCommand. Some data retrieval modes require parameters that define the context for the query. In the example, the first parameter specifies the URL of the Web site where the list can be found, and the second gives the name of the list. Notice that in both cases the Name attribute is used to specify the parameter and the DefaultValue attribute is used to pass a value.

    The parameters in the example are static, set at design time. The control can also accept dynamic parameters where the value that is passed in the parameter is resolved at run-time. You can use most of the parameter classes that are provided by ASP.NET, including the QueryStringParameter class and the ControlParameter class. For example, you could easily modfiy the example markup so that, rather than specifying the name of a list in a static parameter, the name is provided through user interaction with a DropDownList control. The following markup shows how you might attribute a ControlParameter object so that the parameter value is the current selection in a drop-down list.

    <SelectParameters>
        <asp:Parameter Name="WebUrl" DefaultValue="/subsite/" />
        <asp:ControlParameter Name="ListName" ControlID="DropDownList1" PropertyName="SelectedValue" />
    </SelectParameters>
    

    You can also use dynamic parameters in parameterized queries. For more information, see the SelectParameters property.

The SPDataSource class inherits from the DataSourceControl class. As a result, you can bind any control that derives from the DataBoundControl class to an instance of the SPDataSource class. When you are working declaratively, you do this by assigning the value of the SPDataSource control's ID property to the bound control's DataSourceID property, as shown in the next example.

<SharePoint:SPDataSource ID="SPDataSource1" 
    DataSourceMode="List"
    UseInternalName="true" 
    SelectCommand="<View></View>">
    <SelectParameters>
        <asp:Parameter Name="WebUrl" DefaultValue="/subsite/"  />
        <asp:ControlParameter Name="ListName" ControlID="DropDownList1" PropertyName="SelectedValue"  />
    </SelectParameters>
</SharePoint:SPDataSource>

<asp:DropDownList ID="DropDownList1"  AutoPostBack="true">
    <asp:ListItem Selected="True">Contacts</asp:ListItem>
    <asp:ListItem>Customers</asp:ListItem>
</asp:DropDownList>
<br />

<asp:GridView ID="GridView1"  EnableViewState="false"
    DataSourceID="SPDataSource1" 
    AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField HeaderText="First Name" DataField="FirstName" />
        <asp:BoundField HeaderText="Last Name" DataField="Title" />
        <asp:BoundField HeaderText="Business Phone" DataField="WorkPhone" />
        <asp:BoundField HeaderText="Email Address" DataField="Email" />
    </Columns>
</asp:GridView>

When you are working programmatically, you bind to the data source by first assigning the SPDataSource object to the bound control's DataSource property and then calling the bound control's DataBind method.

The SPDataSource control contains data-binding logic, but it does not access the source of the data directly. That task is performed by an instance of a closely associated class, SPDataSourceView. Users of the SPDataSource control do not normally need to interact with the associated SPDataSourceView object. This object is created dynamically, and its properties are set indirectly by setting related and parallel properties of the SPDataSource object.

Note

Unlike other data source controls, the SPDataSource control is associated with only one view. The GetViewNames() method always returns a collection that contains the name of just one data view.

Examples

The following example is a Web Part that binds a GridView control to an SPDataSource control that is set to CrossList mode. This means that the control runs its query across all lists, or all lists of a specified type, wherever they might be within the site collection. In this case, the control queries all lists that were created with the Contacts list template and returns the first and last names of every contact that it finds. The result set populates rows in the bound GridView control.

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.

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

Public Class BoundContactViewer
   Inherits WebPart

   Private grid As GridView
   Private datasource As SPDataSource

   Protected Overrides Sub CreateChildControls()
      MyBase.CreateChildControls()

      ' Instantiate and add the GridView control.
      Me.grid = New GridView()
      Me.Controls.Add(Me.grid)

      ' Instantiate and add the SPDataSource control.
      Me.datasource = New SPDataSource()
      Me.Controls.Add(Me.datasource)

   End Sub

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

      ' Configure the data source for a cross-list query.
      Me.datasource.DataSourceMode = SPDataSourceMode.CrossList
      Me.datasource.SelectCommand = "<Webs Scope='SiteCollection'></Webs>" + _
                                    "<Lists ServerTemplate='105' ></Lists>" + _
                                    "<View>" + _
                                        "<ViewFields>" + _
                                            "<FieldRef Name='Title' />" + _
                                            "<FieldRef Name='FirstName' Nullable='TRUE'/>" + _
                                        "</ViewFields>" + _
                                        "<Query>" + _
                                            "<OrderBy>" + _
                                                "<FieldRef Name='Title' Ascending='TRUE' />" + _
                                            "</OrderBy>" + _
                                        "</Query>" + _
                                    "</View>"
      ' 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)

      ' Format the grid.
      Me.grid.AutoGenerateColumns = False
      Me.grid.AllowSorting = True
      Me.grid.CssClass = "ms-listviewtable"
      Me.grid.AlternatingRowStyle.CssClass = "ms-alternating"
      Me.grid.Width = New Unit(50, UnitType.Percentage)
      Me.grid.GridLines = GridLines.None
      Me.grid.HeaderStyle.Font.Bold = True
      Me.grid.HeaderStyle.HorizontalAlign = HorizontalAlign.Left

      ' Bind to the data source.
      Me.grid.DataSource = Me.datasource
      Me.grid.DataBind()

      Me.grid.RenderControl(writer)

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

namespace SampleWebParts
{
   public class BoundContactViewer : WebPart
   {
      private GridView grid;
      private SPDataSource datasource;

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

         // Instantiate and add the GridView control.
         this.grid = new GridView();
         this.Controls.Add(this.grid);

         // Instantiate and add the SPDataSource control.
         this.datasource = new SPDataSource();
         this.Controls.Add(this.datasource);
      }

      protected override void RenderContents(HtmlTextWriter writer)
      {
         // Configure the data source for a cross-list query.
         this.datasource.DataSourceMode = SPDataSourceMode.CrossList;
         this.datasource.SelectCommand = "<Webs Scope=\"SiteCollection\"></Webs>" +
                                         "<Lists ServerTemplate=\"105\" ></Lists>" +
                                         "<View>" +
                                             "<ViewFields>" +
                                                "<FieldRef Name=\"Title\" />" +
                                                "<FieldRef Name=\"FirstName\" Nullable=\"TRUE\"/>" +
                                              "</ViewFields>" +
                                              "<Query>" +
                                                 "<OrderBy>" +
                                                      "<FieldRef Name=\"Title\" Ascending=\"TRUE\" />" +
                                                 "</OrderBy>" +
                                              "</Query>" +
                                          "</View>";

         // 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);

         // Format the grid.
         this.grid.AutoGenerateColumns = false;
         this.grid.AllowSorting = true;
         this.grid.CssClass = "ms-listviewtable";
         this.grid.AlternatingRowStyle.CssClass = "ms-alternating";
         this.grid.Width = new Unit(50, UnitType.Percentage);
         this.grid.GridLines = GridLines.None;
         this.grid.HeaderStyle.Font.Bold = true;
         this.grid.HeaderStyle.HorizontalAlign = HorizontalAlign.Left;

         // Bind to the data source.
         this.grid.DataSource = this.datasource;
         this.grid.DataBind();

         this.grid.RenderControl(writer);
      }

   }
}

Thread Safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

See Also

Reference

SPDataSource Members

Microsoft.SharePoint.WebControls Namespace

SPSiteDataQuery