The SPDataSource Control
Introduction
SPDataSource, together with XsltListViewWebPart, DataFormWebPart and ContentByQueryWebPart, is one of the most powerful tools that SharePoint provides. Because it can be used in different ways, it can also get complicated. In this post I am going to talk about is different modes and what can they give us. Fist, you need to know that the mode comes from the DataSourceMode property and can be one of:
Let’s see them one by one.
Webs
Webs mode returns subsites of the current site or the root site. You need to supply a select parameter to SPDataSource named WebID, which can take one of the following values:
-
RootWeb: returns subsites of the root site;
-
SubWeb: returns subsites of the current site;
-
<ID>: returns subsites of a given site, indicated by its ID GUID.
You can also pass a WebURL parameter, taking the relative URL of a site, or {sitecollectionroot} for the root site of the current site collection.
SPDataSource will return one row for each site found, and for each site, it will return attributes that correspond to the properties of SPWeb, with the __sp prefix. They are:
__spAlerts
__spAllowAnonymousAccess
__spAllowGlobalCatalog
__spAllowP2P
__spAllProperties
__spAllUsers
__spAlternateCssUrl
__spAlternateHeader
__spAnonymousPermMask64
__spAnonymousState
__spAudit
__spAuthenticationMode
__spAuthor
__spAvailableContentTypes
__spAvailableFields
__spConfiguration
__spContentTypes
__spContext
__spCreated
__spCurrencyLocaleID
__spCurrentChangeToken
__spCurrentUser
__spCustomizationMode
__spCustomJSUrl
__spDataRetrievalServicesSettings
__spDefaultUrl
__spDescription
__spDocTemplates
__spEffectiveBasePermissions
__spEffectivePresenceEnabled
__spEventHandlersEnabled
__spEventReceivers
__spExecuteUrl
__spExists
__spExternalSecurityProviderSetting
__spFeatures
__spFields
__spFieldTypeDefinitionCollection
__spFiles
__spFirstUniqueAncestor
__spFirstUniqueAncestorWeb
__spFirstUniqueRoleDefinitionWeb
__spFolders
__spGroups
__spHasExternalSecurityProvider
__spHasUniquePerm
__spHasUniqueRoleAssignments
__spHasUniqueRoleDefinitions
__spID
__spIgnoreCheckOutLock
__spIncludeSupportingFolders
__spIsADAccountCreationMode
__spIsADEmailEnabled
__spIsParsingWebPartPage
__spIsRootWeb
__spLanguage
__spLastItemModifiedDate
__spLists
__spListTemplates
__spLocale
__spMasterUrl
__spCustomMasterUrl
__spMeetingCount
__spMeetingInformation
__spModules
__spName
__spParentWeb
__spParentWebId
__spPermissions
__spPersonalizationMode
__spPortalMember
__spPortalName
__spPortalSubscriptionUrl
__spPortalUrl
__spPresenceEnabled
__spProperties
__spRecycleBin
__spRegionalSettings
__spReusableAcl
__spRoleAssignments
__spRoleDefinitions
__spRoles
__spRootFolder
__spSafeControls
__spServerNow
__spServerRelativeUrl
__spSite
__spSiteGroups
__spSiteUserInfoList
__spSiteUsers
__spSyndicationEnabled
__spTheme
__spThemeCssUrl
__spTitle
__spTypeCache
__spUrl
__spUserInfoListId
__spUserIsSiteAdmin
__spUserIsWebAdmin
__spUsers
__spViewMode
__spViewStyles
__spWebs
__spWebTemplate
__spWebTemplateId
ListOfLists
ListOfLists returns lists of a given site. It expects a WebID (same values as per the Webs mode) or a WebURL (relative address of a subsite) parameter, if none is supplied, it defaults to the current site. This mode allows restricting the lists to return by applying a CAML query to the SelectCommand property. For example, the following query filters lists of template 101 = Document Library in any of the subsites:
1: <Webs Scope='Recursive'></Webs> <Lists ServerTemplate='101'></Lists>
SPDataSource returns the following fields, which are equivalent to the properties with the same name in the SPList class, minus the __sp prefix:
__spAlertTemplate
__spAllowContentTypes
__spAllowDeletion
__spAllowMultiResponses
__spAnonymousPermMask
__spAnonymousPermMask64
__spAudit
__spAuthor
__spBaseTemplate
__spBaseType
__spCanReceiveEmail
__spContentTypes
__spContentTypesEnabled
__spCreated
__spCurrentChangeToken
__spDefaultView
__spDefaultViewUrl
__spDescription
__spDirection
__spDraftVersionVisibility
__spEffectiveBasePermissions
__spEmailAlias
__spEnableAssignToEmail
__spEnableAttachments
__spEnableMinorVersions
__spEnableModeration
__spEnableSyndication
__spEnableVersioning
__spEventReceivers
__spEventSinkAssembly
__spEventSinkClass
__spEventSinkData
__spExcludeFromTemplate
__spFields
__spFirstUniqueAncestor
__spFlags
__spForceCheckout
__spForms
__spHasExternalEmailHandler
__spHasUniqueRoleAssignments
__spHidden
__spID
__spImageUrl
__spInternalName
__spItemCount
__spItems
__spLastItemDeletedDate
__spLastItemModifiedDate
__spLists
__spMultipleDataList
__spOnQuickLaunch
__spOrdered
__spParentWeb
__spParentWebUrl
__spPermissions
__spProperties
__spPropertiesXml
__spReadSecurity
__spReusableAcl
__spRoleAssignments
__spRootFolder
__spRootFolderUrl
__spSchemaXml
__spSendToLocationName
__spSendToLocationUrl
__spShowUser
__spTitle
__spVersion
__spViews
__spWorkflowAssociations
__spWriteSecurity
CrossList
CrossList performs a query in a number of lists, in pretty much the same way as SPSiteDataQuery does, returning items from these lists. It needs a CAML query in SelectCommand, one that you would pass to SPQuery, and you should specify there the fields to return and an optional query, like the following, which returns all items created by the current user:
1: <Query><Where><Eq><FieldRef Name='Author'/><Value Type='Number'><UserID/></Value></Eq></Where></Query>
Regardless of those, it will always return the following fields:
ListId
WebId
ID
List
List returns items from a single list. It expects a WebID or WebURL parameter, defaulting to the current site if none is present, plus ListName, which is, of course, mandatory, and optionally RootFolder or FolderID (for a starting folder name, from SPFolder.Name, like Path/SubPath, or id, from SPFolder.UniqueId). Do set the UseInternalName and IncludeHidden property to true in SPDataSource. There’s another property that affects the results of List, which is Scope. It is similar to SPQuery. It’s possible values are:
-
Default: shows files and subfolders in the starting folder;
-
Recursive: shows all files in all folders;
-
RecursiveAll: shows all files and all folders;
-
FilesOnly: shows all files in the starting folder.
The fields that are returned depends on the actual list, but the following should be always present:
ContentTypeId
Title
_ModerationComments
File_x0020_Type
HTML_x0020_File_x0020_Type.File_x0020_Type.mapall
HTML_x0020_File_x0020_Type.File_x0020_Type.mapcon
HTML_x0020_File_x0020_Type.File_x0020_Type.mapico
WF4InstanceId
ID
ContentType
Modified
Created
Author
Author.id
Author.title
Author.span
Author.email
Author.sip
Author.jobTitle
Author.department
Author.picture
Editor
Editor.id
Editor.title
Editor.span
Editor.email
Editor.sip
Editor.jobTitle
Editor.department
Editor.picture
_HasCopyDestinations
_HasCopyDestinations.value
_CopySource
owshiddenversion
owshiddenversion.
WorkflowVersion
WorkflowVersion.
_UIVersion
_UIVersion.
_UIVersionString
Attachments
_ModerationStatus
_ModerationStatus.
LinkTitleNoMenu
LinkTitle
LinkTitle2
SelectTitle
InstanceID
InstanceID.
Order
Order.
GUID
WorkflowInstanceID
FileRef
FileRef.urlencode
FileRef.urlencodeasurl
FileDirRef
Last_x0020_Modified
Created_x0020_Date
Created_x0020_Date.ifnew
FSObjType
SortBehavior
PermMask
FileLeafRef
FileLeafRef.Name
FileLeafRef.Suffix
UniqueId
SyncClientId
ProgId
ScopeId
HTML_x0020_File_x0020_Type
_EditMenuTableStart
_EditMenuTableStart2
_EditMenuTableEnd
LinkFilenameNoMenu
LinkFilename
LinkFilename2
DocIcon
ServerUrl
EncodedAbsUrl
BaseName
MetaInfo
MetaInfo.
_Level
_Level.
_IsCurrentVersion
_IsCurrentVersion.value
ItemChildCount
FolderChildCount
AppAuthor
AppEditor
ListItem
Finally, ListItem returns fields from a single list item. You need to feed SPDataSource parameters WebID/WebURL, ListName and ListItemID/ListItemGUID, where ListItemGUID corresponds to the UniqueId property of SPListItem and ListItemID to ID. The fields that are returned depend on the list and content type, of course, but the following are always returned, in the case of a list:
ID
ContentType
Created
Modified
Modified_x0020_By
Created_x0020_By
Or of a document library:
SelectFilename
FileLeafRef
_dlc_DocId
_dlc_DocIdUrl
_dlc_DocIdPersistId
Parameters
Parameters are supplied in the SelectParameters collection and normally are one or more of:
- Parameter: for fixed (hardcoded) values or tokens;
- QueryStringParameter: for passing a parameter in the query string of the URL;
- ControlParameter: for obtaining a value from a control’s property after a postback;
- ProfileParameter: a parameter from the user’s ASP.NET Profile;
- CookieParameter: a parameter from a cookie;
- FormParameter: a value submitted in the page’s form, after a postback;
- SessionParameter: a value from the current ASP.NET session;
- DataFormParameter: for passing names instead of hardcoded list and site IDs.
In SelectCommand, you can use these parameters, by referring their Name inside {}, for example:
1: <View><ViewFields><RowLimit>{Count}</RowLimit></ViewFields></View>
Accessing Result
You can access the results in one of several ways:
- Bind the SPDataSource to a data web part that works with XSLT, such as DataFormWebPart;
- Use a grid control, such as SPGridView, to display fields, but you have to add columns yourself; one disadvantage is that you cannot see the contents of complex properties, such as, for example, __spParentWeb (the ParentWeb property of SPWeb);
- Use instead a data-bound control, such as Repeater, where you can access public properties of returned fields, using Eval, for example, <%# Eval("__spParentWeb.Url") %>.
Conclusion
Together with DataFormWebPart, SPDataSource is a precious tool, which offers great flexibility without going into code. Learn to use it and it will become a great friend!