DataSourceView 類別

定義

作為所有資料來源檢視類別的基底類別,定義資料來源控制項的能力。

public ref class DataSourceView abstract
public abstract class DataSourceView
type DataSourceView = class
Public MustInherit Class DataSourceView
繼承
DataSourceView
衍生

範例

以下程式碼範例示範如何擴展該 DataSourceView 類別,以建立強型別的檢視類別作為資料來源控制。 此 CsVDataSourceView 類別定義了資料來源控制的功能 CsvDataSource ,並提供一個實作,讓資料綁定控制能使用以逗號分隔的值(.csv)檔案中儲存的資料。 欲了解更多資料來源控制的CsvDataSource資訊,請參閱該類別。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

備註

ASP.NET 支援資料綁定架構,使網頁伺服器控制項能以一致的方式綁定資料。 綁定資料的網頁伺服器控制項稱為資料綁定控制項,而促進這種綁定的類別稱為資料來源控制。 資料來源控制項可以代表任何資料來源:關聯式資料庫、檔案、串流、業務物件等等。 資料來源控制項以一致的方式呈現資料給資料綁定控制項,無論底層資料的來源或格式為何。

你會使用 ASP.NET 附帶的資料來源控制,包括 SqlDataSourceAccessDataSourceXmlDataSource,來執行大多數網頁開發任務。 當你想實作自己的自訂資料來源控制時,你會用基底 DataSourceControlDataSourceView 類別。

你可以將資料來源控制視為物件與其相關的資料清單(稱為資料來源檢視)的結合 IDataSource 。 每個資料清單由一個 DataSourceView 物件表示。 這個 DataSourceView 類別是所有與資料來源控制相關的資料來源檢視或資料清單的基底類別。 資料來源檢視定義了資料來源控制的功能。 由於底層資料儲存包含一個或多個資料清單,資料來源控制項總是與一個或多個命名的資料來源檢視相關聯。 資料來源控制項使用方法枚舉目前與資料來源控制相關聯的資料來源檢視,並利用GetViewNamesGetView方法依名稱檢索特定資料來源檢視實例。

所有 DataSourceView 物件都支援使用此 ExecuteSelect 方法從底層資料來源擷取資料。 所有視圖皆可選擇性地支援基本操作,包括 、 ExecuteInsertExecuteUpdate和 等操作ExecuteDelete。 資料綁定控制可以透過使用 GetView and GetViewNames 方法取得相關的資料來源檢視,並在設計時或執行時查詢該檢視來發現資料來源控制的功能。

建構函式

名稱 Description
DataSourceView(IDataSource, String)

初始化 DataSourceView 類別的新執行個體。

屬性

名稱 Description
CanDelete

會取得一個值,表示與目前DataSourceView物件相關聯的DataSourceControl物件是否支援該ExecuteDelete(IDictionary, IDictionary)操作。

CanInsert

會取得一個值,表示與目前DataSourceView物件相關聯的DataSourceControl物件是否支援該ExecuteInsert(IDictionary)操作。

CanPage

會取得一個值,表示與目前DataSourceView物件相關的物件是否DataSourceControl支援透過方法擷取ExecuteSelect(DataSourceSelectArguments)的資料分頁。

CanRetrieveTotalRowCount

會取得一個值,表示與目前DataSourceView物件相關聯的DataSourceControl物件是否支援取得總資料列數,而非資料本身。

CanSort

會取得一個值,表示與目前DataSourceView物件相關聯的DataSourceControl物件是否支援底層資料來源的排序檢視。

CanUpdate

會取得一個值,表示與目前DataSourceView物件相關聯的DataSourceControl物件是否支援該ExecuteUpdate(IDictionary, IDictionary, IDictionary)操作。

Events

會取得資料來源檢視的事件處理代理清單。

Name

會取得資料來源檢視的名稱。

方法

名稱 Description
CanExecute(String)

判斷指定指令是否能執行。

Delete(IDictionary, IDictionary, DataSourceViewOperationCallback)

對物件所代表的資料 DataSourceView 清單執行非同步刪除操作。

Equals(Object)

判斷指定的物件是否等於目前的物件。

(繼承來源 Object)
ExecuteCommand(String, IDictionary, IDictionary, DataSourceViewOperationCallback)

執行指定的命令。

ExecuteCommand(String, IDictionary, IDictionary)

執行指定的命令。

ExecuteDelete(IDictionary, IDictionary)

對物件所代表的資料 DataSourceView 清單執行刪除操作。

ExecuteInsert(IDictionary)

對物件所代表的資料 DataSourceView 清單執行插入操作。

ExecuteSelect(DataSourceSelectArguments)

會從底層資料儲存中取得資料清單。

ExecuteUpdate(IDictionary, IDictionary, IDictionary)

對物件所代表的資料 DataSourceView 清單執行更新操作。

GetHashCode()

做為預設哈希函式。

(繼承來源 Object)
GetType()

取得目前實例的 Type

(繼承來源 Object)
Insert(IDictionary, DataSourceViewOperationCallback)

對物件所代表的資料 DataSourceView 清單執行非同步插入操作。

MemberwiseClone()

建立目前 Object的淺層複本。

(繼承來源 Object)
OnDataSourceViewChanged(EventArgs)

引發 DataSourceViewChanged 事件。

RaiseUnsupportedCapabilityError(DataSourceCapabilities)

由方法呼叫 RaiseUnsupportedCapabilitiesError(DataSourceView) ,用以比較操作所需的 ExecuteSelect(DataSourceSelectArguments) 能力與檢視所支援的能力。

Select(DataSourceSelectArguments, DataSourceViewSelectCallback)

從底層資料儲存中非同步取得資料清單。

ToString()

傳回表示目前 物件的字串。

(繼承來源 Object)
Update(IDictionary, IDictionary, IDictionary, DataSourceViewOperationCallback)

對物件所代表的資料 DataSourceView 清單執行非同步更新操作。

事件

名稱 Description
DataSourceViewChanged

當資料來源視圖改變時會發生。

適用於

另請參閱