Export (0) Print
Expand All

SPDataSource class

Represents SharePoint Foundation data to data-bound controls.

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)

[AspNetHostingPermissionAttribute(SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
[AspNetHostingPermissionAttribute(SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
public class SPDataSource : DataSourceControl, 
	ICloneable

The SPDataSource data source control represents SharePoint Foundation 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" runat="server"
    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 SharePoint Foundation 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. The example assumes that the Web site has two lists, one named Contacts and another named Customers. The example populates a drop down list with the names of those lists so that a user can select one of them at run time, dynamically providing a value for the ListName parameter to the SPDataSource control.

<SharePoint:SPDataSource ID="SPDataSource1" runat="server"
    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" runat="server" AutoPostBack="true">
    <asp:ListItem Selected="True">Contacts</asp:ListItem>
    <asp:ListItem>Customers</asp:ListItem>
</asp:DropDownList>
<br />

<asp:GridView ID="GridView1" runat="server" 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.

NoteNote

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.

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.

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

   }
}

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

Community Additions

Show:
© 2014 Microsoft