DataSourceControl 类
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
作为某些控件的基类,这些控件表示数据绑定控件的的数据源。
public ref class DataSourceControl abstract : System::Web::UI::Control, System::ComponentModel::IListSource, System::Web::UI::IDataSource
[System.ComponentModel.Bindable(false)]
public abstract class DataSourceControl : System.Web.UI.Control, System.ComponentModel.IListSource, System.Web.UI.IDataSource
[<System.ComponentModel.Bindable(false)>]
type DataSourceControl = class
inherit Control
interface IDataSource
interface IListSource
Public MustInherit Class DataSourceControl
Inherits Control
Implements IDataSource, IListSource
- 继承
- 派生
- 属性
- 实现
示例
下面的代码示例演示类如何扩展 DataSourceControl 类。 控件 CsvDataSource
表示存储在 .csv 文件中的逗号分隔文件数据。 类CsvDataSource
提供自己的 、 GetViewNames和其他方法的GetView实现,因为基类实现不起作用。
using System;
using System.Collections;
using System.Data;
using System.IO;
using System.Security.Permissions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
// The CsvDataSource is a data source control that retrieves its
// data from a comma-separated value file.
[AspNetHostingPermission(SecurityAction.Demand, Level=AspNetHostingPermissionLevel.Minimal)]
public class CsvDataSource : DataSourceControl
{
public CsvDataSource() : base() {}
// The comma-separated value file to retrieve data from.
public string FileName {
get {
return ((CsvDataSourceView)this.GetView(String.Empty)).SourceFile;
}
set {
// Only set if it is different.
if ( ((CsvDataSourceView)this.GetView(String.Empty)).SourceFile != value) {
((CsvDataSourceView)this.GetView(String.Empty)).SourceFile = value;
RaiseDataSourceChangedEvent(EventArgs.Empty);
}
}
}
// Do not add the column names as a data row. Infer columns if the CSV file does
// not include column names.
public bool IncludesColumnNames {
get {
return ((CsvDataSourceView)this.GetView(String.Empty)).IncludesColumnNames;
}
set {
// Only set if it is different.
if ( ((CsvDataSourceView)this.GetView(String.Empty)).IncludesColumnNames != value) {
((CsvDataSourceView)this.GetView(String.Empty)).IncludesColumnNames = value;
RaiseDataSourceChangedEvent(EventArgs.Empty);
}
}
}
// Return a strongly typed view for the current data source control.
private CsvDataSourceView view = null;
protected override DataSourceView GetView(string viewName) {
if (null == view) {
view = new CsvDataSourceView(this, String.Empty);
}
return view;
}
// The ListSourceHelper class calls GetList, which
// calls the DataSourceControl.GetViewNames method.
// Override the original implementation to return
// a collection of one element, the default view name.
protected override ICollection GetViewNames() {
ArrayList al = new ArrayList(1);
al.Add(CsvDataSourceView.DefaultViewName);
return al as ICollection;
}
}
// 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();
}
}
Imports System.Collections
Imports System.Data
Imports System.IO
Imports System.Security.Permissions
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Namespace Samples.AspNet.VB.Controls
' The CsvDataSource is a data source control that retrieves its
' data from a comma-separated value file.
<AspNetHostingPermission(SecurityAction.Demand, Level:=AspNetHostingPermissionLevel.Minimal)> _
Public Class CsvDataSource
Inherits DataSourceControl
Public Sub New()
End Sub
' The comma-separated value file to retrieve data from.
Public Property FileName() As String
Get
Return CType(Me.GetView([String].Empty), CsvDataSourceView).SourceFile
End Get
Set
' Only set if it is different.
If CType(Me.GetView([String].Empty), CsvDataSourceView).SourceFile <> value Then
CType(Me.GetView([String].Empty), CsvDataSourceView).SourceFile = value
RaiseDataSourceChangedEvent(EventArgs.Empty)
End If
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.
Public Property IncludesColumnNames() As Boolean
Get
Return CType(Me.GetView([String].Empty), CsvDataSourceView).IncludesColumnNames
End Get
Set
' Only set if it is different.
If CType(Me.GetView([String].Empty), CsvDataSourceView).IncludesColumnNames <> value Then
CType(Me.GetView([String].Empty), CsvDataSourceView).IncludesColumnNames = value
RaiseDataSourceChangedEvent(EventArgs.Empty)
End If
End Set
End Property
' Return a strongly typed view for the current data source control.
Private view As CsvDataSourceView = Nothing
Protected Overrides Function GetView(viewName As String) As DataSourceView
If view Is Nothing Then
view = New CsvDataSourceView(Me, String.Empty)
End If
Return view
End Function 'GetView
' The ListSourceHelper class calls GetList, which
' calls the DataSourceControl.GetViewNames method.
' Override the original implementation to return
' a collection of one element, the default view name.
Protected Overrides Function GetViewNames() As ICollection
Dim al As New ArrayList(1)
al.Add(CsvDataSourceView.DefaultViewName)
Return CType(al, ICollection)
End Function 'GetViewNames
End Class
' 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
End Namespace
下面的代码示例演示如何在 Web 窗体中使用 CsvDataSource
控件。
<%@ Page Language="C#" %>
<%@ Register Tagprefix="aspSample"
Namespace="Samples.AspNet.CS.Controls" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>ASP.NET Example</title>
</head>
<body>
<form id="form1" runat="server">
<asp:gridview
id="GridView1"
runat="server"
allowsorting="True"
datasourceid="CsvDataSource1" />
<aspSample:CsvDataSource
id = "CsvDataSource1"
runat = "server"
filename = "sample.csv"
includescolumnnames="True" />
</form>
</body>
</html>
<%@ Page Language="VB" %>
<%@ Register Tagprefix="aspSample"
Namespace="Samples.AspNet.VB.Controls" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>ASP.NET Example</title>
</head>
<body>
<form id="form1" runat="server">
<asp:gridview
id="GridView1"
runat="server"
allowsorting="True"
datasourceid="CsvDataSource1" />
<aspSample:CsvDataSource
id = "CsvDataSource1"
runat = "server"
filename = "sample.csv"
includescolumnnames="True" />
</form>
</body>
</html>
注解
ASP.NET 支持控件数据绑定体系结构,该体系结构使 Web 服务器控件能够以一致的方式绑定到数据。 绑定到数据的 Web 服务器控件称为数据绑定控件,促进该绑定的类称为数据源控件。 数据源控件可以表示任何数据源:关系数据库、文件、流、业务对象等。 无论基础数据的源或格式如何,数据源控件都以一致的方式向数据绑定控件呈现数据。
使用随 ASP.NET 提供的数据源控件(包括 SqlDataSource、 AccessDataSource和 XmlDataSource)来执行大多数 Web 开发任务。 如果要实现自己的自定义数据源控件,请使用基 DataSourceControl 类。
虽然实现 IDataSource 接口的任何类都是数据源控件,但大多数 ASP.NET 数据源控件都扩展了抽象 DataSourceControl 类,后者提供接口的基本 IDataSource 实现。 类 DataSourceControl 还提供 接口的 IListSource 实现,使你能够以编程方式将数据源控件分配给 DataSource
数据绑定控件的 属性,并将数据作为基本列表返回给控件。
派生自 DataBoundControl 类的任何 ASP.NET 控件都可以绑定到数据源控件。
DataBoundControl当 绑定到数据源控件时,会在运行时自动执行数据绑定。 还可以将数据源控件与 ASP.NET 控件结合使用,这些控件公开 DataSource
或 DataSourceID
属性并支持基本数据绑定,但不派生自 DataBoundControl。 使用这些数据绑定控件时,必须显式调用 DataBind
方法。 有关数据绑定的详细信息,请参阅 ASP.NET 数据访问内容映射。
可以将数据源控件视为 对象及其关联的数据列表(称为数据源视图)的组合 DataSourceControl 。 每个数据列表都由 一个 DataSourceView 对象表示。 由于基础数据存储包含一个或多个数据列表,因此 DataSourceControl 始终与一个或多个命名 DataSourceView 对象相关联。 接口 IDataSource 定义所有数据源控件用于与数据源视图交互的方法: GetViewNames 方法用于枚举当前与数据源控件关联的数据源视图,方法 GetView 用于按名称检索特定的数据源视图实例。
还可以将数据源控件视为调用方用于访问数据的两个不同的接口。 类 DataSourceControl 是页面开发人员在开发 Web 窗体页时直接与其交互的接口, DataSourceView 类是数据绑定控件和数据绑定控件作者与之交互的接口。 由于对象 DataSourceView 仅在运行时可用,因此数据源控件或数据源视图保留的任何状态都必须由数据源控件直接公开。
没有 ASP.NET 数据源控件的可视呈现;它们作为控件实现,以便你可以以声明方式创建它们,并选择性地允许它们参与状态管理。 因此,数据源控件不支持 或 SkinID等EnableTheming视觉功能。
构造函数
DataSourceControl() |
初始化 DataSourceControl 类的新实例。 |
属性
Adapter |
获取控件的浏览器特定适配器。 (继承自 Control) |
AppRelativeTemplateSourceDirectory |
获取或设置包含该控件的 Page 或 UserControl 对象的应用程序相对虚拟目录。 (继承自 Control) |
BindingContainer |
获取包含该控件的数据绑定的控件。 (继承自 Control) |
ChildControlsCreated |
获取一个值,该值指示是否已创建服务器控件的子控件。 (继承自 Control) |
ClientID |
获取由 ASP.NET 生成的服务器控件标识符。 |
ClientIDMode |
此属性不用于数据源控件。 |
ClientIDMode |
获取或设置用于生成 ClientID 属性值的算法。 (继承自 Control) |
ClientIDSeparator |
获取一个字符值,该值表示 ClientID 属性中使用的分隔符字符。 (继承自 Control) |
Context |
为当前 Web 请求获取与服务器控件关联的 HttpContext 对象。 (继承自 Control) |
Controls |
获取 ControlCollection 对象,该对象表示 UI 层次结构中的指定服务器控件的子控件。 |
DataItemContainer |
如果命名容器实现 IDataItemContainer,则获取对命名容器的引用。 (继承自 Control) |
DataKeysContainer |
如果命名容器实现 IDataKeysControl,则获取对命名容器的引用。 (继承自 Control) |
DesignMode |
获取一个值,该值指示是否正在使用设计图面上的一个控件。 (继承自 Control) |
EnableTheming |
获取一个值,该值指示此控件是否支持主题。 |
EnableViewState |
获取或设置一个值,该值指示服务器控件是否向发出请求的客户端保持自己的视图状态以及它所包含的任何子控件的视图状态。 (继承自 Control) |
Events |
获取控件的事件处理程序委托列表。 此属性为只读。 (继承自 Control) |
HasChildViewState |
获取一个值,该值指示当前服务器控件的子控件是否具有任何已保存的视图状态设置。 (继承自 Control) |
ID |
获取或设置分配给服务器控件的编程标识符。 (继承自 Control) |
IdSeparator |
获取用于分隔控件标识符的字符。 (继承自 Control) |
IsChildControlStateCleared |
获取一个值,该值指示该控件中包含的控件是否具有控件状态。 (继承自 Control) |
IsTrackingViewState |
获取一个值,用于指示服务器控件是否会将更改保存到其视图状态中。 (继承自 Control) |
IsViewStateEnabled |
获取一个值,该值指示是否为该控件启用了视图状态。 (继承自 Control) |
LoadViewStateByID |
获取一个值,该值指示控件是否通过 ID 而不是索引参与加载其视图状态。 (继承自 Control) |
NamingContainer |
获取对服务器控件的命名容器的引用,此引用创建唯一的命名空间,以区分具有相同 ID 属性值的服务器控件。 (继承自 Control) |
Page |
获取对包含服务器控件的 Page 实例的引用。 (继承自 Control) |
Parent |
获取对页 UI 层次结构中服务器控件的父控件的引用。 (继承自 Control) |
RenderingCompatibility |
获取一个值,该值指定呈现的 HTML 将与之兼容的 ASP.NET 版本。 (继承自 Control) |
Site |
获取容器信息,该容器在呈现于设计图面上时承载当前控件。 (继承自 Control) |
SkinID |
获取要应用于 DataSourceControl 控件的外观。 |
TemplateControl |
获取或设置对包含该控件的模板的引用。 (继承自 Control) |
TemplateSourceDirectory |
获取包含当前服务器控件的 Page 或 UserControl 的虚拟目录。 (继承自 Control) |
UniqueID |
获取服务器控件的唯一的、以分层形式限定的标识符。 (继承自 Control) |
ValidateRequestMode |
获取或设置指示控件是否检查来自浏览器的客户端输入是否具有潜在危险值的值。 (继承自 Control) |
ViewState |
获取状态信息的字典,这些信息使您可以在同一页的多个请求间保存和还原服务器控件的视图状态。 (继承自 Control) |
ViewStateIgnoresCase |
获取一个值,该值指示 StateBag 对象是否不区分大小写。 (继承自 Control) |
ViewStateMode |
获取或设置此控件的视图状态模式。 (继承自 Control) |
Visible |
获取或设置一个值,该值指示是否以可视化方式显示控件。 |
方法
事件
DataBinding |
当服务器控件绑定到数据源时发生。 (继承自 Control) |
Disposed |
当从内存释放服务器控件时发生,这是请求 ASP.NET 页时服务器控件生存期的最后阶段。 (继承自 Control) |
Init |
当服务器控件初始化时发生;初始化是控件生存期的第一步。 (继承自 Control) |
Load |
当服务器控件加载到 Page 对象中时发生。 (继承自 Control) |
PreRender |
在加载 Control 对象之后、呈现之前发生。 (继承自 Control) |
Unload |
当服务器控件从内存中卸载时发生。 (继承自 Control) |
显式接口实现
扩展方法
FindDataSourceControl(Control) |
返回与指定控件的数据控件关联的数据源。 |
FindFieldTemplate(Control, String) |
返回指定控件的命名容器中指定列的字段模板。 |
FindMetaTable(Control) |
返回包含数据控件的元表对象。 |
GetDefaultValues(IDataSource) |
为指定数据源获取默认值的集合。 |
GetMetaTable(IDataSource) |
获取指定数据源对象中表的元数据。 |
TryGetMetaTable(IDataSource, MetaTable) |
确定表元数据是否可用。 |