DataSourceView Klasa

Definicja

Służy jako klasa bazowa dla wszystkich klas widoku źródła danych, które definiują możliwości kontrolek źródła danych.

public ref class DataSourceView abstract
public abstract class DataSourceView
type DataSourceView = class
Public MustInherit Class DataSourceView
Dziedziczenie
DataSourceView
Pochodne

Przykłady

W poniższym przykładzie kodu pokazano, jak rozszerzyć klasę w DataSourceView celu utworzenia silnie typizowanej klasy widoku dla kontroli źródła danych. Klasa CsVDataSourceView definiuje możliwości CsvDataSource kontroli źródła danych i zapewnia implementację kontrolek powiązanych z danymi w celu używania danych przechowywanych w plikach wartości rozdzielanych przecinkami (.csv). Aby uzyskać więcej informacji na CsvDataSource temat kontroli źródła danych, zobacz klasę DataSourceControl .

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

Uwagi

ASP.NET obsługuje architekturę powiązania danych, która umożliwia kontrolkom serwera sieci Web powiązanie z danymi w spójny sposób. Kontrolki serwera internetowego powiązane z danymi są określane jako kontrolki powiązane z danymi oraz klasy, które ułatwiają tworzenie powiązań, są nazywane kontrolkami źródła danych. Kontrolki źródła danych mogą reprezentować dowolne źródło danych: relacyjną bazę danych, plik, strumień, obiekt biznesowy itd. Kontrolki źródła danych przedstawiają dane w spójny sposób na kontrolki powiązane z danymi, niezależnie od źródła lub formatu danych bazowych.

Aby wykonać większość zadań związanych z programowaniem w Internecie, należy użyć kontrolek źródła danych dostarczanych z ASP.NET, w tym SqlDataSource, AccessDataSourcei XmlDataSource. Klas i DataSourceView bazowych DataSourceControl należy używać, gdy chcesz zaimplementować własną niestandardową kontrolę źródła danych.

Kontrolkę źródła danych można traktować jako kombinację IDataSource obiektu i skojarzonych z nim list danych, nazywanych widokami źródła danych. Każda lista danych jest reprezentowana DataSourceView przez obiekt. Klasa DataSourceView jest klasą bazową dla wszystkich widoków źródeł danych lub list danych skojarzonych z kontrolkami źródła danych. Widoki źródła danych definiują możliwości kontroli źródła danych. Ponieważ podstawowy magazyn danych zawiera co najmniej jedną listę danych, kontrolka źródła danych jest zawsze skojarzona z co najmniej jednym nazwanym widokiem źródła danych. Kontrolka źródła danych używa GetViewNames metody do wyliczania widoków źródła danych skojarzonych obecnie z kontrolą źródła danych i GetView metody w celu pobrania określonego wystąpienia widoku źródła danych według nazwy.

Wszystkie DataSourceView obiekty obsługują pobieranie danych z bazowego źródła danych przy użyciu ExecuteSelect metody . Wszystkie widoki opcjonalnie obsługują podstawowy zestaw operacji, w tym operacje, takie jak ExecuteInsert, ExecuteUpdatei ExecuteDelete. Kontrolka powiązana z danymi umożliwia odnajdywanie możliwości kontroli źródła danych przez pobieranie skojarzonego widoku źródła danych przy użyciu GetView metod i GetViewNames oraz wykonywanie zapytań względem widoku w czasie projektowania lub w czasie wykonywania.

Konstruktory

DataSourceView(IDataSource, String)

Inicjuje nowe wystąpienie klasy DataSourceView.

Właściwości

CanDelete

Pobiera wartość wskazującą, czy DataSourceView obiekt skojarzony z bieżącym DataSourceControl obiektem obsługuje operację ExecuteDelete(IDictionary, IDictionary) .

CanInsert

Pobiera wartość wskazującą, czy DataSourceView obiekt skojarzony z bieżącym DataSourceControl obiektem obsługuje operację ExecuteInsert(IDictionary) .

CanPage

Pobiera wartość wskazującą, czy DataSourceView obiekt skojarzony z bieżącym DataSourceControl obiektem obsługuje stronicowanie danych pobranych przez metodę ExecuteSelect(DataSourceSelectArguments) .

CanRetrieveTotalRowCount

Pobiera wartość wskazującą, czy DataSourceView obiekt skojarzony z bieżącym DataSourceControl obiektem obsługuje pobieranie całkowitej liczby wierszy danych zamiast danych.

CanSort

Pobiera wartość wskazującą, czy DataSourceView obiekt skojarzony z bieżącym DataSourceControl obiektem obsługuje posortowany widok w bazowym źródle danych.

CanUpdate

Pobiera wartość wskazującą, czy DataSourceView obiekt skojarzony z bieżącym DataSourceControl obiektem obsługuje operację ExecuteUpdate(IDictionary, IDictionary, IDictionary) .

Events

Pobiera listę delegatów procedury obsługi zdarzeń dla widoku źródła danych.

Name

Pobiera nazwę widoku źródła danych.

Metody

CanExecute(String)

Określa, czy można wykonać określone polecenie.

Delete(IDictionary, IDictionary, DataSourceViewOperationCallback)

Wykonuje asynchroniczną operację usuwania na liście danych reprezentowanych przez DataSourceView obiekt.

Equals(Object)

Określa, czy dany obiekt jest taki sam, jak bieżący obiekt.

(Odziedziczone po Object)
ExecuteCommand(String, IDictionary, IDictionary)

Wykonuje określone polecenie.

ExecuteCommand(String, IDictionary, IDictionary, DataSourceViewOperationCallback)

Wykonuje określone polecenie.

ExecuteDelete(IDictionary, IDictionary)

Wykonuje operację usuwania na liście danych reprezentowanych przez DataSourceView obiekt.

ExecuteInsert(IDictionary)

Wykonuje operację wstawiania na liście danych reprezentowanych przez DataSourceView obiekt.

ExecuteSelect(DataSourceSelectArguments)

Pobiera listę danych z magazynu danych bazowych.

ExecuteUpdate(IDictionary, IDictionary, IDictionary)

Wykonuje operację aktualizacji na liście danych reprezentowanych przez DataSourceView obiekt.

GetHashCode()

Służy jako domyślna funkcja skrótu.

(Odziedziczone po Object)
GetType()

Type Pobiera wartość bieżącego wystąpienia.

(Odziedziczone po Object)
Insert(IDictionary, DataSourceViewOperationCallback)

Wykonuje operację asynchronicznego wstawiania na liście danych reprezentowanych przez DataSourceView obiekt.

MemberwiseClone()

Tworzy płytkią kopię bieżącego Objectelementu .

(Odziedziczone po Object)
OnDataSourceViewChanged(EventArgs)

DataSourceViewChanged Zgłasza zdarzenie.

RaiseUnsupportedCapabilityError(DataSourceCapabilities)

Wywołana przez metodę RaiseUnsupportedCapabilitiesError(DataSourceView) w celu porównania możliwości żądanych dla ExecuteSelect(DataSourceSelectArguments) operacji względem tych, które obsługuje widok.

Select(DataSourceSelectArguments, DataSourceViewSelectCallback)

Pobiera listę danych asynchronicznie z bazowego magazynu danych.

ToString()

Zwraca ciąg reprezentujący bieżący obiekt.

(Odziedziczone po Object)
Update(IDictionary, IDictionary, IDictionary, DataSourceViewOperationCallback)

Wykonuje asynchroniczną operację aktualizacji na liście danych reprezentowanych przez DataSourceView obiekt.

Zdarzenia

DataSourceViewChanged

Występuje, gdy widok źródła danych uległ zmianie.

Dotyczy

Zobacz też