DataSourceView DataSourceView DataSourceView DataSourceView Class

定义

用作所有数据源视图类的基类,这些视图类定义数据源控件的功能。Serves as the base class for all data source view classes, which define the capabilities of data source controls.

public ref class DataSourceView abstract
public abstract class DataSourceView
type DataSourceView = class
Public MustInherit Class DataSourceView
继承
DataSourceViewDataSourceViewDataSourceViewDataSourceView
派生

示例

下面的代码示例演示如何扩展DataSourceView类以为数据源控件创建强类型视图类。The following code example demonstrates how to extend the DataSourceView class to create a strongly typed view class for a data source control. 类定义CsvDataSource数据源控件的功能, 并为数据绑定控件提供一个实现, 以使用存储在逗号分隔值 (.csv) 文件中的数据。 CsVDataSourceViewThe CsVDataSourceView class defines the capabilities of the CsvDataSource data source control and provides an implementation for data-bound controls to use data stored in comma-separated value (.csv) files. 有关CsvDataSource数据源控件的详细信息, DataSourceControl请参阅类。For more information on the CsvDataSource data source control, see the DataSourceControl class.

// 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 支持一种数据绑定体系结构, 使 Web 服务器控件能够以一致的方式绑定到数据。ASP.NET supports a data-binding architecture that enables Web server controls to bind to data in a consistent fashion. 绑定到数据的 Web 服务器控件被称为数据绑定控件, 而用于简化绑定的类称为数据源控件。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.

使用随 ASP.NET 提供的数据源控件 (包括SqlDataSourceAccessDataSourceXmlDataSource) 来执行大多数 Web 开发任务。You use the data source controls that are provided with ASP.NET, including SqlDataSource, AccessDataSource, and XmlDataSource, to perform most Web development tasks. 如果要实现自己DataSourceControlDataSourceView自定义数据源控件, 请使用基和类。You use the base DataSourceControl and DataSourceView classes when you want to implement your own custom data source control.

您可以将数据源控件看作是IDataSource对象及其关联的数据列表 (称为数据源视图) 的组合。You can think of a data source control as the combination of the IDataSource object and its associated lists of data, called data source views. 每个数据列表由一个DataSourceView对象表示。Each list of data is represented by a DataSourceView object. DataSourceView类是与数据源控件关联的所有数据源视图或数据列表的基类。The DataSourceView class is the base class for all data source views, or lists of data, associated with data source controls. 数据源视图定义数据源控件的功能。Data source views define the capabilities of a data source control. 由于基础数据存储包含一个或多个数据列表, 因此数据源控件始终与一个或多个命名数据源视图相关联。Because the underlying data storage contains one or more lists of data, a data source control is always associated with one or more named data source views. 数据源控件使用GetViewNames方法来枚举当前与数据源控件关联的数据源视图GetView , 并使用方法来按名称检索特定的数据源视图实例。The data source control uses the GetViewNames method to enumerate the data source views currently associated with the data source control and the GetView method to retrieve a specific data source view instance by name.

所有DataSourceView对象均支持ExecuteSelect使用方法从基础数据源中检索数据。All DataSourceView objects support data retrieval from the underlying data source using the ExecuteSelect method. 所有视图都可以选择支持一组基本操作, 其中包括ExecuteInsertExecuteUpdateExecuteDelete等操作。All views optionally support a basic set of operations, including operations such as ExecuteInsert, ExecuteUpdate, and ExecuteDelete. 数据绑定控件可以通过使用GetViewGetViewNames方法检索关联的数据源视图, 以及在设计时或运行时查询视图来发现数据源控件的功能。A data-bound control can discover the capabilities of a data source control by retrieving an associated data source view using the GetView and GetViewNames methods, and by querying the view at design time or run time.

构造函数

DataSourceView(IDataSource, String) DataSourceView(IDataSource, String) DataSourceView(IDataSource, String) DataSourceView(IDataSource, String)

初始化 DataSourceView 类的新实例。Initializes a new instance of the DataSourceView class.

属性

CanDelete CanDelete CanDelete CanDelete

获取一个值,该值指示与当前 DataSourceControl 对象关联的 DataSourceView 对象是否支持 ExecuteDelete(IDictionary, IDictionary) 操作。Gets a value indicating whether the DataSourceView object associated with the current DataSourceControl object supports the ExecuteDelete(IDictionary, IDictionary) operation.

CanInsert CanInsert CanInsert CanInsert

获取一个值,该值指示与当前 DataSourceControl 对象关联的 DataSourceView 对象是否支持 ExecuteInsert(IDictionary) 操作。Gets a value indicating whether the DataSourceView object associated with the current DataSourceControl object supports the ExecuteInsert(IDictionary) operation.

CanPage CanPage CanPage CanPage

获取一个值,该值指示与当前 DataSourceControl 对象关联的 DataSourceView 对象是否支持对通过 ExecuteSelect(DataSourceSelectArguments) 方法检索到的数据进行分页。Gets a value indicating whether the DataSourceView object associated with the current DataSourceControl object supports paging through the data retrieved by the ExecuteSelect(DataSourceSelectArguments) method.

CanRetrieveTotalRowCount CanRetrieveTotalRowCount CanRetrieveTotalRowCount CanRetrieveTotalRowCount

获取一个值,该值指示与当前 DataSourceControl 对象关联的 DataSourceView 对象是否支持检索数据的总行数(而不是数据)。Gets a value indicating whether the DataSourceView object associated with the current DataSourceControl object supports retrieving the total number of data rows, instead of the data.

CanSort CanSort CanSort CanSort

获取一个值,该值指示与当前 DataSourceControl 对象关联的 DataSourceView 对象是否支持基础数据源的排序视图。Gets a value indicating whether the DataSourceView object associated with the current DataSourceControl object supports a sorted view on the underlying data source.

CanUpdate CanUpdate CanUpdate CanUpdate

获取一个值,该值指示与当前 DataSourceControl 对象关联的 DataSourceView 对象是否支持 ExecuteUpdate(IDictionary, IDictionary, IDictionary) 操作。Gets a value indicating whether the DataSourceView object associated with the current DataSourceControl object supports the ExecuteUpdate(IDictionary, IDictionary, IDictionary) operation.

Events Events Events Events

获取数据源视图的事件处理程序委托的列表。Gets a list of event-handler delegates for the data source view.

Name Name Name Name

获取数据源视图的名称。Gets the name of the data source view.

方法

CanExecute(String) CanExecute(String) CanExecute(String) CanExecute(String)

确定是否能执行指定命令。Determines whether the specified command can be executed.

Delete(IDictionary, IDictionary, DataSourceViewOperationCallback) Delete(IDictionary, IDictionary, DataSourceViewOperationCallback) Delete(IDictionary, IDictionary, DataSourceViewOperationCallback) Delete(IDictionary, IDictionary, DataSourceViewOperationCallback)

DataSourceView 对象所表示的数据列表执行异步删除操作。Performs an asynchronous delete operation on the list of data that the DataSourceView object represents.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

确定指定的对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(Inherited from Object)
ExecuteCommand(String, IDictionary, IDictionary) ExecuteCommand(String, IDictionary, IDictionary) ExecuteCommand(String, IDictionary, IDictionary) ExecuteCommand(String, IDictionary, IDictionary)

执行指定的命令。Executes the specified command.

ExecuteCommand(String, IDictionary, IDictionary, DataSourceViewOperationCallback) ExecuteCommand(String, IDictionary, IDictionary, DataSourceViewOperationCallback) ExecuteCommand(String, IDictionary, IDictionary, DataSourceViewOperationCallback) ExecuteCommand(String, IDictionary, IDictionary, DataSourceViewOperationCallback)

执行指定的命令。Executes the specified command.

ExecuteDelete(IDictionary, IDictionary) ExecuteDelete(IDictionary, IDictionary) ExecuteDelete(IDictionary, IDictionary) ExecuteDelete(IDictionary, IDictionary)

DataSourceView 对象所表示的数据列表执行删除操作。Performs a delete operation on the list of data that the DataSourceView object represents.

ExecuteInsert(IDictionary) ExecuteInsert(IDictionary) ExecuteInsert(IDictionary) ExecuteInsert(IDictionary)

DataSourceView 对象所表示的数据列表执行插入操作。Performs an insert operation on the list of data that the DataSourceView object represents.

ExecuteSelect(DataSourceSelectArguments) ExecuteSelect(DataSourceSelectArguments) ExecuteSelect(DataSourceSelectArguments) ExecuteSelect(DataSourceSelectArguments)

从基础数据存储获取数据列表。Gets a list of data from the underlying data storage.

ExecuteUpdate(IDictionary, IDictionary, IDictionary) ExecuteUpdate(IDictionary, IDictionary, IDictionary) ExecuteUpdate(IDictionary, IDictionary, IDictionary) ExecuteUpdate(IDictionary, IDictionary, IDictionary)

DataSourceView 对象所表示的数据列表执行更新操作。Performs an update operation on the list of data that the DataSourceView object represents.

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

作为默认哈希函数。Serves as the default hash function.

(Inherited from Object)
GetType() GetType() GetType() GetType()

获取当前实例的 TypeGets the Type of the current instance.

(Inherited from Object)
Insert(IDictionary, DataSourceViewOperationCallback) Insert(IDictionary, DataSourceViewOperationCallback) Insert(IDictionary, DataSourceViewOperationCallback) Insert(IDictionary, DataSourceViewOperationCallback)

DataSourceView 对象所表示的数据列表执行异步插入操作。Performs an asynchronous insert operation on the list of data that the DataSourceView object represents.

MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(Inherited from Object)
OnDataSourceViewChanged(EventArgs) OnDataSourceViewChanged(EventArgs) OnDataSourceViewChanged(EventArgs) OnDataSourceViewChanged(EventArgs)

引发 DataSourceViewChanged 事件。Raises the DataSourceViewChanged event.

RaiseUnsupportedCapabilityError(DataSourceCapabilities) RaiseUnsupportedCapabilityError(DataSourceCapabilities) RaiseUnsupportedCapabilityError(DataSourceCapabilities) RaiseUnsupportedCapabilityError(DataSourceCapabilities)

RaiseUnsupportedCapabilitiesError(DataSourceView) 方法调用,用于将 ExecuteSelect(DataSourceSelectArguments) 操作所请求的功能与视图所支持的功能进行比较。Called by the RaiseUnsupportedCapabilitiesError(DataSourceView) method to compare the capabilities requested for an ExecuteSelect(DataSourceSelectArguments) operation against those that the view supports.

Select(DataSourceSelectArguments, DataSourceViewSelectCallback) Select(DataSourceSelectArguments, DataSourceViewSelectCallback) Select(DataSourceSelectArguments, DataSourceViewSelectCallback) Select(DataSourceSelectArguments, DataSourceViewSelectCallback)

从基础数据存储中异步获取数据列表。Gets a list of data asynchronously from the underlying data storage.

ToString() ToString() ToString() ToString()

返回表示当前对象的字符串。Returns a string that represents the current object.

(Inherited from Object)
Update(IDictionary, IDictionary, IDictionary, DataSourceViewOperationCallback) Update(IDictionary, IDictionary, IDictionary, DataSourceViewOperationCallback) Update(IDictionary, IDictionary, IDictionary, DataSourceViewOperationCallback) Update(IDictionary, IDictionary, IDictionary, DataSourceViewOperationCallback)

DataSourceView 对象所表示的数据列表执行异步更新操作。Performs an asynchronous update operation on the list of data that the DataSourceView object represents.

事件

DataSourceViewChanged DataSourceViewChanged DataSourceViewChanged DataSourceViewChanged

在数据源视图更改时发生。Occurs when the data source view has changed.

适用于

另请参阅