Export (0) Print
Expand All

IDataSource Interface

Represents an abstract data source that data-bound controls bind to.

Namespace:  System.Web.UI
Assembly:  System.Web (in System.Web.dll)

Public Interface IDataSource

The IDataSource type exposes the following members.

Public methodGetViewGets the named data source view associated with the data source control.
Public methodGetViewNamesGets a collection of names representing the list of view objects associated with the IDataSource interface.

Public eventDataSourceChangedOccurs when a data source control has changed in some way that affects data-bound controls.

Public Extension MethodGetDefaultValuesGets the collection of the default values for the specified data source. (Defined by DynamicDataExtensions.)
Public Extension MethodGetMetaTableGets the metadata for a table in the specified data source object. (Defined by DynamicDataExtensions.)
Public Extension MethodTryGetMetaTableDetermines whether table metadata is available. (Defined by DynamicDataExtensions.)

ASP.NET supports a control data-binding architecture that enables Web server controls to bind to data in a consistent fashion. Web server controls that bind to data are referred to as data-bound controls, and the classes that facilitate that binding are called data source controls. Data source controls can represent any data source: a relational database, a file, a stream, a business object, and so on. Data source controls present data in a consistent way to data-bound controls, regardless of the source or format of the underlying data.

You implement the IDataSource interface when you want to implement your own custom ASP.NET data source control.

Any class that implements the IDataSource interface is a data source control. The IDataSource interface serves as the foundation for all ASP.NET data source controls and defines one of the fundamental data-binding architecture concepts with its two methods: the GetView method and the GetViewNames method. This concept is that all data source controls support one or more named views on their data. The data source view object is similar to the DataView abstraction in the System.Data namespace: a data-bindable, customized view of data for sorting, filtering, and other data operations that the view defines. At its core, a data source control does nothing more than retrieve views on data.

A data source control can have one or more associated data source view objects. Some data source controls, including those that represent relational databases such as SqlDataSource and AccessDataSource, support only one view. Other data source controls, including hierarchical data source controls such as SiteMapDataSource, support many views. The data source view defines the capabilities of a data source and the operations that it supports.

In summary, data source controls implement the IDataSource interface, support one or more named views on the data they represent, and always support data retrieval from the data source they represent. Data source controls always retrieve data on demand, such as when DataBind is called on a data bound control.

The following code example demonstrates how a class can implement the methods defined by the IDataSource interface to provide data to data-bound controls. The data source control in this example acts as a data source on a comma-separated value file, and can be used by any data-bound control to display comma-separated file data. This code example is part of a larger example provided for the DataSourceControl class.

Imports System
Imports System.Collections
Imports System.Data
Imports System.IO
Imports System.Security.Permissions
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls

Namespace Samples.AspNet.VB.Controls

' The CsvDataSource is a data source control that retrieves its 
' data from a comma-separated value file.
<AspNetHostingPermission(SecurityAction.Demand, Level:=AspNetHostingPermissionLevel.Minimal)> _
Public Class CsvDataSource
   Inherits DataSourceControl

   Public Sub New()
   End Sub 'New 

   ' The comma-separated value file to retrieve data from. 
   Public Property FileName() As String 
         Return CType(Me.GetView([String].Empty), CsvDataSourceView).SourceFile
      End Get 
         ' Only set if it is different. 
         If CType(Me.GetView([String].Empty), CsvDataSourceView).SourceFile <> value Then 
            CType(Me.GetView([String].Empty), CsvDataSourceView).SourceFile = value
         End If 
      End Set 
   End Property 

   ' Do not add the column names as a data row. Infer columns if the CSV file does 
   ' not include column names. 

   Public Property IncludesColumnNames() As Boolean 
         Return CType(Me.GetView([String].Empty), CsvDataSourceView).IncludesColumnNames
      End Get 
         ' Only set if it is different. 
         If CType(Me.GetView([String].Empty), CsvDataSourceView).IncludesColumnNames <> value Then 
            CType(Me.GetView([String].Empty), CsvDataSourceView).IncludesColumnNames = value
         End If 
      End Set 
   End Property 

   ' Return a strongly typed view for the current data source control. 
   Private view As CsvDataSourceView = Nothing 

   Protected Overrides Function GetView(viewName As String) As DataSourceView
      If view Is Nothing Then
         view = New CsvDataSourceView(Me, String.Empty)
      End If 
      Return view
   End Function 'GetView

   ' The ListSourceHelper class calls GetList, which 
   ' calls the DataSourceControl.GetViewNames method. 
   ' Override the original implementation to return 
   ' a collection of one element, the default view name. 
   Protected Overrides Function GetViewNames() As ICollection
      Dim al As New ArrayList(1)
      Return CType(al, ICollection)
   End Function 'GetViewNames

End Class 'CsvDataSource

' The CsvDataSourceView class encapsulates the 
' capabilities of the CsvDataSource data source control. 

Public Class CsvDataSourceView
   Inherits DataSourceView

   Public Sub New(owner As IDataSource, name As String)
       MyBase.New(owner, DefaultViewName)
   End Sub 'New 

   ' The data source view is named. However, the CsvDataSource 
   ' only supports one view, so the name is ignored, and the 
   ' default name used instead. 
   Public Shared DefaultViewName As String = "CommaSeparatedView" 

   ' The location of the .csv file. 
   Private aSourceFile As String = [String].Empty

   Friend Property SourceFile() As String 
         Return aSourceFile
      End Get 
         ' Use MapPath when the SourceFile is set, so that files local to the 
         ' current directory can be easily used. 
         Dim mappedFileName As String
         mappedFileName = HttpContext.Current.Server.MapPath(value)
         aSourceFile = mappedFileName
      End Set 
   End Property 

   ' Do not add the column names as a data row. Infer columns if the CSV file does 
   ' not include column names. 
   Private columns As Boolean = False 

   Friend Property IncludesColumnNames() As Boolean 
         Return columns
      End Get 
         columns = value
      End Set 
   End Property 

   ' Get data from the underlying data source. 
   ' Build and return a DataView, regardless of mode. 
   Protected Overrides Function ExecuteSelect(selectArgs As DataSourceSelectArguments) _
    As System.Collections.IEnumerable
      Dim dataList As IEnumerable = Nothing 
      ' Open the .csv file. 
      If File.Exists(Me.SourceFile) Then 
         Dim data As New DataTable()

         ' Open the file to read from. 
         Dim sr As StreamReader = File.OpenText(Me.SourceFile)

            ' Parse the line 
            Dim dataValues() As String 
            Dim col As DataColumn

            ' Do the following to add schema.
            dataValues = sr.ReadLine().Split(","c)
            ' For each token in the comma-delimited string, add a column 
            ' to the DataTable schema. 
            Dim token As String 
            For Each token In dataValues
               col = New DataColumn(token, System.Type.GetType("System.String"))
            Next token

            ' Do not add the first row as data if the CSV file includes column names. 
            If Not IncludesColumnNames Then
               data.Rows.Add(CopyRowData(dataValues, data.NewRow()))
            End If 

            ' Do the following to add data. 
            Dim s As String 
               s = sr.ReadLine()
               If Not s Is Nothing Then
                   dataValues = s.Split(","c)
                   data.Rows.Add(CopyRowData(dataValues, data.NewRow()))
               End If 
            Loop Until s Is Nothing 

         End Try

         Dim dataView As New DataView(data)
         If Not selectArgs.SortExpression Is String.Empty Then
             dataView.Sort = selectArgs.SortExpression
         End If
         dataList = dataView
         Throw New System.Configuration.ConfigurationErrorsException("File not found, " + Me.SourceFile)
      End If 

      If dataList is Nothing Then 
         Throw New InvalidOperationException("No data loaded from data source.")
      End If 

      Return dataList
   End Function 'ExecuteSelect

   Private Function CopyRowData([source]() As String, target As DataRow) As DataRow
         Dim i As Integer 
         For i = 0 To [source].Length - 1
            target(i) = [source](i)
         Next i
      Catch iore As IndexOutOfRangeException
         ' There are more columns in this row than 
         ' the original schema allows.  Stop copying 
         ' and return the DataRow. 
         Return target
      End Try 
      Return target
   End Function 'CopyRowData

   ' The CsvDataSourceView does not currently 
   ' permit deletion. You can modify or extend 
   ' this sample to do so. 
   Public Overrides ReadOnly Property CanDelete() As Boolean 
         Return False 
      End Get 
   End Property 

   Protected Overrides Function ExecuteDelete(keys As IDictionary, values As IDictionary) As Integer 
      Throw New NotSupportedException()
   End Function 'ExecuteDelete

   ' The CsvDataSourceView does not currently 
   ' permit insertion of a new record. You can 
   ' modify or extend this sample to do so. 
   Public Overrides ReadOnly Property CanInsert() As Boolean 
         Return False 
      End Get 
   End Property 

   Protected Overrides Function ExecuteInsert(values As IDictionary) As Integer 
      Throw New NotSupportedException()
   End Function 'ExecuteInsert

   ' The CsvDataSourceView does not currently 
   ' permit update operations. You can modify or 
   ' extend this sample to do so. 
   Public Overrides ReadOnly Property CanUpdate() As Boolean 
         Return False 
      End Get 
   End Property 

   Protected Overrides Function ExecuteUpdate(keys As IDictionary, _
                                              values As IDictionary, _
                                              oldValues As IDictionary) As Integer 
      Throw New NotSupportedException()
   End Function 'ExecuteUpdate

End Class 'CsvDataSourceView
End Namespace

.NET Framework

Supported in: 4.5.2, 4.5.1, 4.5, 4, 3.5, 3.0, 2.0

Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

© 2014 Microsoft