DataSourceView Classe

Definizione

Funge da classe base per tutte le classi di visualizzazione origine dati, che definiscono le funzionalità dei controlli origine dati.

public ref class DataSourceView abstract
public abstract class DataSourceView
type DataSourceView = class
Public MustInherit Class DataSourceView
Ereditarietà
DataSourceView
Derivato

Esempio

Nell'esempio di codice seguente viene illustrato come estendere la DataSourceView classe per creare una classe di visualizzazione fortemente tipizzata per un controllo origine dati. La CsVDataSourceView classe definisce le funzionalità del controllo origine dati e fornisce un'implementazione per i controlli associati ai dati per l'uso CsvDataSource dei dati archiviati in file con valori delimitati da virgole (.csv). Per altre informazioni sul CsvDataSource controllo origine dati, vedere la DataSourceControl classe .

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

Commenti

ASP.NET supporta un'architettura di data binding che consente ai controlli server Web di associare ai dati in modo coerente. I controlli server Web associati ai dati vengono definiti controlli associati ai dati e le classi che facilitano l'associazione vengono denominati controlli origine dati. I controlli origine dati possono rappresentare qualsiasi origine dati: un database relazionale, un file, un flusso, un oggetto business e così via. I controlli origine dati presentano dati in modo coerente ai controlli associati ai dati, indipendentemente dall'origine o dal formato dei dati sottostanti.

Per eseguire la maggior parte delle attività di sviluppo Web, usare i controlli origine dati forniti con ASP.NET, inclusi SqlDataSource, AccessDataSourcee , XmlDataSource. Usare le classi e DataSourceView di base DataSourceControl quando si vuole implementare il proprio controllo origine dati personalizzato.

È possibile pensare a un controllo origine dati come combinazione dell'oggetto IDataSource e degli elenchi associati di dati, denominati viste origine dati. Ogni elenco di dati è rappresentato da un DataSourceView oggetto. La DataSourceView classe è la classe di base per tutte le visualizzazioni dell'origine dati o gli elenchi di dati associati ai controlli origine dati. Le visualizzazioni origine dati definiscono le funzionalità di un controllo origine dati. Poiché l'archiviazione dati sottostante contiene uno o più elenchi di dati, un controllo origine dati è sempre associato a una o più viste di origine dati denominate. Il controllo origine dati usa il GetViewNames metodo per enumerare le visualizzazioni dell'origine dati attualmente associate al controllo origine dati e al metodo per recuperare un'istanza GetView specifica della vista origine dati in base al nome.

Tutti gli DataSourceView oggetti supportano il recupero dei dati dall'origine dati sottostante usando il ExecuteSelect metodo . Tutte le visualizzazioni supportano facoltativamente un set di operazioni di base, incluse operazioni come ExecuteInsert, ExecuteUpdatee ExecuteDelete. Un controllo associato ai dati può individuare le funzionalità di un controllo origine dati recuperando una visualizzazione origine dati associata usando i GetView metodi e GetViewNames e eseguendo query sulla visualizzazione in fase di progettazione o in fase di esecuzione.

Costruttori

DataSourceView(IDataSource, String)

Inizializza una nuova istanza della classe DataSourceView.

Proprietà

CanDelete

Ottiene un valore che indica se l'oggetto DataSourceView associato all'oggetto DataSourceControl corrente supporta l'operazione ExecuteDelete(IDictionary, IDictionary).

CanInsert

Ottiene un valore che indica se l'oggetto DataSourceView associato all'oggetto DataSourceControl corrente supporta l'operazione ExecuteInsert(IDictionary).

CanPage

Ottiene un valore che indica se l'oggetto DataSourceView associato all'oggetto DataSourceControl corrente supporta lo spostamento dei dati recuperati tramite il metodo ExecuteSelect(DataSourceSelectArguments).

CanRetrieveTotalRowCount

Ottiene un valore che indica se l'oggetto DataSourceView associato all'oggetto DataSourceControl corrente supporta il recupero del numero totale di righe di dati anziché dei dati.

CanSort

Ottiene un valore che indica se l'oggetto DataSourceView associato all'oggetto DataSourceControl corrente supporta una visualizzazione ordinata dell'origine dati sottostante.

CanUpdate

Ottiene un valore che indica se l'oggetto DataSourceView associato all'oggetto DataSourceControl corrente supporta l'operazione ExecuteUpdate(IDictionary, IDictionary, IDictionary).

Events

Ottiene un elenco di delegati del gestore eventi per la visualizzazione origine dati.

Name

Ottiene il nome della visualizzazione origine dati.

Metodi

CanExecute(String)

Determina se è possibile eseguire il comando specificato.

Delete(IDictionary, IDictionary, DataSourceViewOperationCallback)

Esegue un'operazione di eliminazione asincrona sull'elenco di dati rappresentato dall'oggetto DataSourceView.

Equals(Object)

Determina se l'oggetto specificato è uguale all'oggetto corrente.

(Ereditato da Object)
ExecuteCommand(String, IDictionary, IDictionary)

Esegue il comando specificato.

ExecuteCommand(String, IDictionary, IDictionary, DataSourceViewOperationCallback)

Esegue il comando specificato.

ExecuteDelete(IDictionary, IDictionary)

Esegue un'operazione di eliminazione sull'elenco di dati rappresentato dall'oggetto DataSourceView.

ExecuteInsert(IDictionary)

Esegue un'operazione di inserimento sull'elenco di dati rappresentato dall'oggetto DataSourceView.

ExecuteSelect(DataSourceSelectArguments)

Ottiene un elenco di dati dall'archivio dati sottostante.

ExecuteUpdate(IDictionary, IDictionary, IDictionary)

Esegue un'operazione di aggiornamento sull'elenco di dati rappresentato dall'oggetto DataSourceView.

GetHashCode()

Funge da funzione hash predefinita.

(Ereditato da Object)
GetType()

Ottiene l'oggetto Type dell'istanza corrente.

(Ereditato da Object)
Insert(IDictionary, DataSourceViewOperationCallback)

Esegue un'operazione di inserimento asincrona sull'elenco di dati rappresentato dall'oggetto DataSourceView.

MemberwiseClone()

Crea una copia superficiale dell'oggetto Object corrente.

(Ereditato da Object)
OnDataSourceViewChanged(EventArgs)

Genera l'evento DataSourceViewChanged.

RaiseUnsupportedCapabilityError(DataSourceCapabilities)

Viene chiamato dal metodo RaiseUnsupportedCapabilitiesError(DataSourceView) per confrontare le funzionalità richieste per un'operazione ExecuteSelect(DataSourceSelectArguments) con quelle supportate dalla visualizzazione.

Select(DataSourceSelectArguments, DataSourceViewSelectCallback)

Ottiene un elenco di dati dall'archivio dati sottostante in modo asincrono.

ToString()

Restituisce una stringa che rappresenta l'oggetto corrente.

(Ereditato da Object)
Update(IDictionary, IDictionary, IDictionary, DataSourceViewOperationCallback)

Esegue un'operazione di aggiornamento asincrona sull'elenco di dati rappresentato dall'oggetto DataSourceView.

Eventi

DataSourceViewChanged

Si verifica quando la visualizzazione origine dati ha subito una modifica.

Si applica a

Vedi anche