DataSourceView Clase

Definición

Sirve de clase base para todas las clases de vista de origen de datos, que definen las funciones de los controles de origen de datos.

public ref class DataSourceView abstract
public abstract class DataSourceView
type DataSourceView = class
Public MustInherit Class DataSourceView
Herencia
DataSourceView
Derivado

Ejemplos

En el ejemplo de código siguiente se muestra cómo extender la DataSourceView clase para crear una clase de vista fuertemente tipada para un control de origen de datos. La CsVDataSourceView clase define las funciones del CsvDataSource control de origen de datos y proporciona una implementación para que los controles enlazados a datos usen datos almacenados en archivos de valores separados por comas (.csv). Para obtener más información sobre el control de CsvDataSource origen de datos, vea la DataSourceControl clase .

// The CsvDataSourceView class encapsulates the
// capabilities of the CsvDataSource data source control.
public class CsvDataSourceView : DataSourceView
{

    public CsvDataSourceView(IDataSource owner, string name) :base(owner, DefaultViewName) {
    }

    // 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 static string DefaultViewName = "CommaSeparatedView";

    // The location of the .csv file.
    private string sourceFile = String.Empty;
    internal string SourceFile {
        get {
            return sourceFile;
        }
        set {
            // Use MapPath when the SourceFile is set, so that files local to the
            // current directory can be easily used.
            string mappedFileName = HttpContext.Current.Server.MapPath(value);
            sourceFile = mappedFileName;
        }
    }

    // Do not add the column names as a data row. Infer columns if the CSV file does
    // not include column names.
    private bool columns = false;
    internal bool IncludesColumnNames {
        get {
            return columns;
        }
        set {
            columns = value;
        }
    }

    // Get data from the underlying data source.
    // Build and return a DataView, regardless of mode.
    protected override IEnumerable ExecuteSelect(DataSourceSelectArguments selectArgs) {
        IEnumerable dataList = null;
        // Open the .csv file.
        if (File.Exists(this.SourceFile)) {
            DataTable data = new DataTable();

            // Open the file to read from.
            using (StreamReader sr = File.OpenText(this.SourceFile)) {
                // Parse the line
                string s = "";
                string[] dataValues;
                DataColumn col;

                // Do the following to add schema.
                dataValues = sr.ReadLine().Split(',');
                // For each token in the comma-delimited string, add a column
                // to the DataTable schema.
                foreach (string token in dataValues) {
                    col = new DataColumn(token,typeof(string));
                    data.Columns.Add(col);
                }

                // Do not add the first row as data if the CSV file includes column names.
                if (! IncludesColumnNames)
                    data.Rows.Add(CopyRowData(dataValues, data.NewRow()));

                // Do the following to add data.
                while ((s = sr.ReadLine()) != null) {
                    dataValues = s.Split(',');
                    data.Rows.Add(CopyRowData(dataValues, data.NewRow()));
                }
            }
            data.AcceptChanges();
            DataView dataView = new DataView(data);
            if (!string.IsNullOrEmpty(selectArgs.SortExpression)) {
                dataView.Sort = selectArgs.SortExpression;
            }
            dataList = dataView;
        }
        else {
            throw new System.Configuration.ConfigurationErrorsException("File not found, " + this.SourceFile);
        }

        if (null == dataList) {
            throw new InvalidOperationException("No data loaded from data source.");
        }

        return dataList;
    }

    private DataRow CopyRowData(string[] source, DataRow target) {
        try {
            for (int i = 0;i < source.Length;i++) {
                target[i] = source[i];
            }
        }
        catch (System.IndexOutOfRangeException) {
            // There are more columns in this row than
            // the original schema allows.  Stop copying
            // and return the DataRow.
            return target;
        }
        return target;
    }
    // The CsvDataSourceView does not currently
    // permit deletion. You can modify or extend
    // this sample to do so.
    public override bool CanDelete {
        get {
            return false;
        }
    }
    protected override int ExecuteDelete(IDictionary keys, IDictionary values)
    {
        throw new NotSupportedException();
    }
    // The CsvDataSourceView does not currently
    // permit insertion of a new record. You can
    // modify or extend this sample to do so.
    public override bool CanInsert {
        get {
            return false;
        }
    }
    protected override int ExecuteInsert(IDictionary values)
    {
        throw new NotSupportedException();
    }
    // The CsvDataSourceView does not currently
    // permit update operations. You can modify or
    // extend this sample to do so.
    public override bool CanUpdate {
        get {
            return false;
        }
    }
    protected override int ExecuteUpdate(IDictionary keys, IDictionary values, IDictionary oldValues)
    {
        throw new NotSupportedException();
    }
}
' 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

   ' 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
      Get
         Return aSourceFile
      End Get
      Set
         ' 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
      Get
         Return columns
      End Get
      Set
         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)

         Try
            ' 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"))
               data.Columns.Add(col)
            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
            Do
               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

         Finally
            sr.Close()
         End Try

         data.AcceptChanges()
         Dim dataView As New DataView(data)
         If Not selectArgs.SortExpression Is String.Empty Then
             dataView.Sort = selectArgs.SortExpression
         End If
         dataList = dataView
      Else
         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
      Try
         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
      Get
         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
      Get
         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
      Get
         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

Comentarios

ASP.NET admite una arquitectura de enlace de datos que permite que los controles de servidor web se enlacen a datos de forma coherente. Los controles de servidor web que se enlazan a datos se conocen como controles enlazados a datos y las clases que facilitan ese enlace se denominan controles de origen de datos. Los controles de origen de datos pueden representar cualquier origen de datos: una base de datos relacional, un archivo, un flujo, un objeto de negocio, etc. Los controles de origen de datos presentan datos de forma coherente a los controles enlazados a datos, independientemente del origen o formato de los datos subyacentes.

Use los controles de origen de datos que se proporcionan con ASP.NET, incluidos SqlDataSource, AccessDataSourcey XmlDataSource, para realizar la mayoría de las tareas de desarrollo web. Use las DataSourceControl clases base y DataSourceView cuando quiera implementar su propio control de origen de datos personalizado.

Puede considerar un control de origen de datos como la combinación del IDataSource objeto y sus listas de datos asociadas, denominadas vistas del origen de datos. Cada lista de datos se representa mediante un DataSourceView objeto . La DataSourceView clase es la clase base para todas las vistas del origen de datos, o listas de datos, asociadas a los controles de origen de datos. Las vistas del origen de datos definen las funcionalidades de un control de origen de datos. Dado que el almacenamiento de datos subyacente contiene una o varias listas de datos, un control de origen de datos siempre está asociado a una o varias vistas de origen de datos con nombre. El control de origen de datos usa el GetViewNames método para enumerar las vistas del origen de datos asociadas actualmente con el control de origen de datos y el GetView método para recuperar una instancia de vista del origen de datos específica por nombre.

Todos los DataSourceView objetos admiten la recuperación de datos del origen de datos subyacente mediante el ExecuteSelect método . Todas las vistas admiten opcionalmente un conjunto básico de operaciones, incluidas operaciones como ExecuteInsert, ExecuteUpdatey ExecuteDelete. Un control enlazado a datos puede detectar las funciones de un control de origen de datos recuperando una vista de origen de datos asociada mediante los GetView métodos y GetViewNames y consultando la vista en tiempo de diseño o en tiempo de ejecución.

Constructores

DataSourceView(IDataSource, String)

Inicializa una nueva instancia de la clase DataSourceView.

Propiedades

CanDelete

Obtiene un valor que indica si el objeto DataSourceView asociado al objeto DataSourceControl actual admite la operación ExecuteDelete(IDictionary, IDictionary).

CanInsert

Obtiene un valor que indica si el objeto DataSourceView asociado al objeto DataSourceControl actual admite la operación ExecuteInsert(IDictionary).

CanPage

Obtiene un valor que indica si el objeto DataSourceView asociado al objeto DataSourceControl actual admite la paginación de los datos recuperados por el método ExecuteSelect(DataSourceSelectArguments).

CanRetrieveTotalRowCount

Obtiene un valor que indica si el objeto DataSourceView asociado al objeto DataSourceControl actual admite la recuperación del número total de filas de datos, en lugar de los propios datos.

CanSort

Obtiene un valor que indica si el objeto DataSourceView asociado al objeto DataSourceControl actual admite la vista ordenada en el origen de datos subyacente.

CanUpdate

Obtiene un valor que indica si el objeto DataSourceView asociado al objeto DataSourceControl actual admite la operación ExecuteUpdate(IDictionary, IDictionary, IDictionary).

Events

Obtiene una lista de delegados de controladores de eventos de la vista de origen de datos.

Name

Obtiene el nombre de la vista de datos de origen.

Métodos

CanExecute(String)

Determina si se puede ejecutar el comando especificado.

Delete(IDictionary, IDictionary, DataSourceViewOperationCallback)

Realiza una operación de eliminación asincrónica en la lista de datos que el objeto DataSourceView representa.

Equals(Object)

Determina si el objeto especificado es igual que el objeto actual.

(Heredado de Object)
ExecuteCommand(String, IDictionary, IDictionary)

Ejecuta el comando especificado.

ExecuteCommand(String, IDictionary, IDictionary, DataSourceViewOperationCallback)

Ejecuta el comando especificado.

ExecuteDelete(IDictionary, IDictionary)

Realiza una operación de eliminación en la lista de datos que el objeto DataSourceView representa.

ExecuteInsert(IDictionary)

Realiza una operación de inserción en la lista de datos que el objeto DataSourceView representa.

ExecuteSelect(DataSourceSelectArguments)

Obtiene una lista de datos del espacio de almacenamiento de datos subyacente.

ExecuteUpdate(IDictionary, IDictionary, IDictionary)

Realiza una operación de actualización en la lista de datos que el objeto DataSourceView representa.

GetHashCode()

Sirve como la función hash predeterminada.

(Heredado de Object)
GetType()

Obtiene el Type de la instancia actual.

(Heredado de Object)
Insert(IDictionary, DataSourceViewOperationCallback)

Realiza una operación de inserción asincrónica en la lista de datos que el objeto DataSourceView representa.

MemberwiseClone()

Crea una copia superficial del Object actual.

(Heredado de Object)
OnDataSourceViewChanged(EventArgs)

Genera el evento DataSourceViewChanged.

RaiseUnsupportedCapabilityError(DataSourceCapabilities)

El método RaiseUnsupportedCapabilitiesError(DataSourceView) llama a este método para comparar las funciones solicitadas para una operación de ExecuteSelect(DataSourceSelectArguments) con las funciones que admite la vista.

Select(DataSourceSelectArguments, DataSourceViewSelectCallback)

Obtiene, de forma asincrónica, una lista de datos del espacio de almacenamiento de datos subyacente.

ToString()

Devuelve una cadena que representa el objeto actual.

(Heredado de Object)
Update(IDictionary, IDictionary, IDictionary, DataSourceViewOperationCallback)

Realiza una operación de actualización asincrónica en la lista de datos que el objeto DataSourceView representa.

Eventos

DataSourceViewChanged

Se produce cuando la vista de origen de datos ha cambiado.

Se aplica a

Consulte también