DataView 类

定义

代表 DataTable 的可绑定数据的自定义视图,它用于排序、筛选、搜索、编辑和导航。Represents a databindable, customized view of a DataTable for sorting, filtering, searching, editing, and navigation. DataView 不存储数据,而改为表示对应的 DataTable 的连接视图。The DataView does not store data, but instead represents a connected view of its corresponding DataTable. 更改 DataView 的数据会影响 DataTableChanges to the DataView's data will affect the DataTable. 更改 DataTable 的数据将影响与之关联的所有 DataViewChanges to the DataTable's data will affect all DataViews associated with it.

public ref class DataView : System::ComponentModel::MarshalByValueComponent, System::Collections::IList, System::ComponentModel::IBindingListView, System::ComponentModel::ISupportInitializeNotification, System::ComponentModel::ITypedList
public class DataView : System.ComponentModel.MarshalByValueComponent, System.Collections.IList, System.ComponentModel.IBindingListView, System.ComponentModel.ISupportInitializeNotification, System.ComponentModel.ITypedList
type DataView = class
    inherit MarshalByValueComponent
    interface IBindingListView
    interface ITypedList
    interface ISupportInitializeNotification
    interface IBindingList
    interface IList
    interface ICollection
    interface IEnumerable
    interface ISupportInitialize
Public Class DataView
Inherits MarshalByValueComponent
Implements IBindingListView, IList, ISupportInitializeNotification, ITypedList
继承
实现

示例

下面的示例创建一个具有DataTable一个列和五行的单个行。The following example creates a single DataTable with one column and five rows. DataView创建两个对象RowStateFilter , 并将每个对象设置为显示表数据的不同视图。Two DataView objects are created and the RowStateFilter is set on each to show different views of the table data. 然后打印这些值。The values are then printed.

using System;
using System.Xml;
using System.Data;
using System.Data.Common;
using System.Windows.Forms;

public class Form1: Form
{
    protected DataSet DataSet1;
    protected DataGrid dataGrid1;



    private void DemonstrateDataView()
    {
        // Create one DataTable with one column.
        DataTable table = new DataTable("table");
        DataColumn colItem = new DataColumn("item",
            Type.GetType("System.String"));
        table.Columns.Add(colItem);

        // Add five items.
        DataRow NewRow;
        for(int i = 0; i <5; i++)
        {
            NewRow = table.NewRow();
            NewRow["item"] = "Item " + i;
            table.Rows.Add(NewRow);
        }
        // Change the values in the table.
        table.AcceptChanges();
        table.Rows[0]["item"]="cat";
        table.Rows[1]["item"] = "dog";
 
        // Create two DataView objects with the same table.
        DataView firstView = new DataView(table);
        DataView secondView = new DataView(table);
 
        // Print current table values.
        PrintTableOrView(table,"Current Values in Table");
    
        // Set first DataView to show only modified 
        // versions of original rows.
        firstView.RowStateFilter=DataViewRowState.ModifiedOriginal;

        // Print values.   
        PrintTableOrView(firstView,"First DataView: ModifiedOriginal");

        // Add one New row to the second view.
        DataRowView rowView;
        rowView=secondView.AddNew();
        rowView["item"] = "fish";

        // Set second DataView to show modified versions of 
        // current rows, or New rows.
        secondView.RowStateFilter=DataViewRowState.ModifiedCurrent 
            | DataViewRowState.Added;
        // Print modified and Added rows.
        PrintTableOrView(secondView, 
            "Second DataView: ModifiedCurrent | Added");
    }
 
    private void PrintTableOrView(DataTable table, string label)
    {
        // This function prints values in the table or DataView.
        Console.WriteLine("\n" + label);
        for(int i = 0; i<table.Rows.Count;i++)
        {
            Console.WriteLine("\table" + table.Rows[i]["item"]);
        }
        Console.WriteLine();
    }
 
    private void PrintTableOrView(DataView view, string label)
    {
 
        // This overload prints values in the table or DataView.
        Console.WriteLine("\n" + label);
        for(int i = 0; i<view.Count;i++)
        {
            Console.WriteLine("\table" + view[i]["item"]);
        }
        Console.WriteLine();
    }
}
Private Sub DemonstrateDataView()
    ' Create one DataTable with one column.
    Dim table As New DataTable("table")
    Dim colItem As New DataColumn("item", _
        Type.GetType("System.String"))
    table.Columns.Add(colItem)

    ' Add five items.
    Dim NewRow As DataRow
    Dim i As Integer
    For i = 0 To 4
    
    NewRow = table.NewRow()
    NewRow("item") = "Item " & i
    table.Rows.Add(NewRow)
    Next
    table.AcceptChanges()

    ' Create two DataView objects with the same table.
    Dim firstView As New DataView(table)
    Dim secondView As New DataView(table)
    
    ' Change the values in the table.
    table.Rows(0)("item") = "cat"
    table.Rows(1)("item") = "dog"
    
    ' Print current table values.
    PrintTableOrView(table, "Current Values in Table")
        
    ' Set first DataView to show only modified versions of original rows.
    firstView.RowStateFilter = DataViewRowState.ModifiedOriginal

    ' Print values.    
    PrintTableOrView(firstView, "First DataView: ModifiedOriginal")

    ' Add one New row to the second view.
    Dim rowView As DataRowView
    rowView = secondView.AddNew()
    rowView("item") = "fish"
    ' Set second DataView to show modified versions of 
    ' current rows, or New rows.
    secondView.RowStateFilter = DataViewRowState.ModifiedCurrent _
        Or DataViewRowState.Added
    ' Print modified and Added rows.
    PrintTableOrView(secondView, _
        "Second DataView: ModifiedCurrent or Added")
End Sub
    
Overloads Private Sub PrintTableOrView( _
    ByVal view As DataView, ByVal label As String)
    Console.WriteLine(label)
    Dim i As Integer
    For i = 0 To view.count - 1
    
    Console.WriteLine(view(i)("item"))
    Next
    Console.WriteLine()
End Sub
    
Overloads Private Sub PrintTableOrView( _
    ByVal table As DataTable, ByVal label As String)
    Console.WriteLine(label)
    Dim i As Integer
    For i = 0 To table.Rows.Count - 1
    Console.WriteLine(table.Rows(i)("item"))
    Next
    Console.WriteLine()
End Sub

下面的示例将创建DataView按总计LINQ to DataSetLINQ to DataSet排序的联机订单:The following example creates a DataView of online orders ordered by total due from a LINQ to DataSetLINQ to DataSet query:

DataTable orders = dataSet.Tables["SalesOrderHeader"];

EnumerableRowCollection<DataRow> query =
    from order in orders.AsEnumerable()
    where order.Field<bool>("OnlineOrderFlag") == true
    orderby order.Field<decimal>("TotalDue")
    select order;

DataView view = query.AsDataView();

bindingSource1.DataSource = view;
Dim orders As DataTable = dataSet.Tables("SalesOrderHeader")

Dim query = _
    From order In orders.AsEnumerable() _
    Where order.Field(Of Boolean)("OnlineOrderFlag") = True _
    Order By order.Field(Of Decimal)("TotalDue") _
    Select order

Dim view As DataView = query.AsDataView()
bindingSource1.DataSource = view

注解

的主要功能DataView是允许在 Windows 窗体和 Web 窗体上进行数据绑定。A major function of the DataView is to allow for data binding on both Windows Forms and Web Forms.

此外, DataView还可以自定义以显示DataTable中的数据子集。Additionally, a DataView can be customized to present a subset of data from the DataTable. 利用此功能, 您可以将两个控件绑定DataTable到同一个, 但这会显示不同版本的数据。This capability lets you have two controls bound to the same DataTable, but that show different versions of the data. 例如, 一个控件可能绑定到DataView显示表中所有行的, 另一个控件可能配置为仅显示已DataTable从中删除的行。For example, one control might be bound to a DataView that shows all the rows in the table, and a second might be configured to display only the rows that have been deleted from the DataTable. DataTableDefaultView具有属性。The DataTable also has a DefaultView property. 这将返回表DataView的默认值。This returns the default DataView for the table. 例如, 如果要对表创建自定义视图, 请RowFilter DataView在返回DefaultView的上设置。For example, if you want to create a custom view on the table, set the RowFilter on the DataView returned by the DefaultView.

若要创建数据的筛选和排序视图, 请设置RowFilterSort属性。To create a filtered and sorted view of data, set the RowFilter and Sort properties. 然后, 使用Item[Int32]属性返回单个DataRowViewThen, use the Item[Int32] property to return a single DataRowView.

还可以使用AddNewDelete方法在行集中添加和删除。You can also add and delete from the set of rows using the AddNew and Delete methods. 当你使用这些方法时, RowStateFilter属性可以设置为指定只显示已删除DataView的行或新行。When you use those methods, the RowStateFilter property can set to specify that only deleted rows or new rows be displayed by the DataView.

备注

如果未显式DataView指定的排序条件, 则中DataViewDataRowView对象将基于中DataTable.Rows对应DataRow DataRowCollection的 DataView 的索引进行排序。If you do not explicitly specify sort criteria for DataView, the DataRowView objects in DataView are sorted based on the index of DataView's corresponding DataRow in the DataTable.Rows DataRowCollection.

LINQ to DataSetLINQ to DataSet允许开发人员通过使用DataSet LINQLINQ创建复杂、功能强大的查询。allows developers to create complex, powerful queries over a DataSet by using LINQLINQ. DataRow但是, LINQ to DataSetLINQ to DataSet查询返回的是对象的枚举, 但在绑定方案中并不容易使用。A LINQ to DataSetLINQ to DataSet query returns an enumeration of DataRow objects, however, which is not easily used in a binding scenario. DataView可以通过LINQ to DataSetLINQ to DataSet查询创建, 并对该查询进行筛选和排序。DataView can be created from a LINQ to DataSetLINQ to DataSet query and takes on the filtering and sorting characteristics of that query. LINQ to DataSetLINQ to DataSet通过提供DataView LINQLINQ基于表达式的筛选和排序来扩展的功能, 这允许执行比基于字符串的筛选和排序更复杂、功能强大的筛选和排序操作。extends the functionality of the DataView by providing LINQLINQ expression-based filtering and sorting, which allows for much more complex and powerful filtering and sorting operations than string-based filtering and sorting. 有关详细信息, 请参阅数据绑定和 LINQ to DataSetSee Data Binding and LINQ to DataSet for more information.

构造函数

DataView()

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

DataView(DataTable)

使用指定的 DataView 初始化 DataTable 类的新实例。Initializes a new instance of the DataView class with the specified DataTable.

DataView(DataTable, String, String, DataViewRowState)

使用指定的 DataTableRowFilterSortDataViewRowState 初始化 DataView 类的新实例。Initializes a new instance of the DataView class with the specified DataTable, RowFilter, Sort, and DataViewRowState.

属性

AllowDelete

设置或获取一个值,该值指示是否允许删除。Sets or gets a value that indicates whether deletes are allowed.

AllowEdit

获取或设置一个值,该值指示是否允许编辑。Gets or sets a value that indicates whether edits are allowed.

AllowNew

获取或设置一个值,该值指示是否可以通过使用 AddNew() 方法添加新行。Gets or sets a value that indicates whether the new rows can be added by using the AddNew() method.

ApplyDefaultSort

获取或设置一个值,该值指示是否使用默认排序。Gets or sets a value that indicates whether to use the default sort. 默认排序是通过 PrimaryKey 指定的所有主键进行排序(升序)。The default sort is (ascending) by all primary keys as specified by PrimaryKey.

Container

获取组件的容器。Gets the container for the component.

(继承自 MarshalByValueComponent)
Count

在应用 RowFilterRowStateFilter 之后,获取 DataView 中的记录数。Gets the number of records in the DataView after RowFilter and RowStateFilter have been applied.

DataViewManager

获取与此视图关联的 DataViewManagerGets the DataViewManager associated with this view.

DesignMode

获取指示组件当前是否处于设计模式的值。Gets a value indicating whether the component is currently in design mode.

(继承自 MarshalByValueComponent)
Events

获取附加到该组件的事件处理程序的列表。Gets the list of event handlers that are attached to this component.

(继承自 MarshalByValueComponent)
IsInitialized

获取一个值,该值指示组件是否已初始化。Gets a value that indicates whether the component is initialized.

IsOpen

获取一个值,该值指示数据源当前是否打开并投影 DataTable 上的数据视图。Gets a value that indicates whether the data source is currently open and projecting views of data on the DataTable.

Item[Int32]

从指定的表中获取数据行。Gets a row of data from a specified table.

RowFilter

获取或设置用于筛选在 DataView 中查看哪些行的表达式。Gets or sets the expression used to filter which rows are viewed in the DataView.

RowStateFilter

获取或设置用于 DataView 中的行状态筛选器。Gets or sets the row state filter used in the DataView.

Site

获取或设置组件的位置。Gets or sets the site of the component.

(继承自 MarshalByValueComponent)
Sort

获取或设置 DataView 的一个或多个排序列和排序顺序。Gets or sets the sort column or columns, and sort order for the DataView.

Table

获取或设置源 DataTableGets or sets the source DataTable.

方法

AddNew()

DataView 中添加新行。Adds a new row to the DataView.

BeginInit()

开始初始化在窗体上使用或由另一个组件使用的 DataViewStarts the initialization of a DataView that is used on a form or used by another component. 此初始化在运行时发生。The initialization occurs at runtime.

Close()

关闭 DataViewCloses the DataView.

ColumnCollectionChanged(Object, CollectionChangeEventArgs)

在成功更改 DataColumnCollection 后发生。Occurs after a DataColumnCollection has been changed successfully.

CopyTo(Array, Int32)

将项复制到数组中。Copies items into an array. 仅适用于 Web 窗体界面。Only for Web Forms Interfaces.

Delete(Int32)

删除指定索引处的行。Deletes a row at the specified index.

Dispose()

释放由 MarshalByValueComponent 使用的所有资源。Releases all resources used by the MarshalByValueComponent.

(继承自 MarshalByValueComponent)
Dispose(Boolean)

释放由 DataView 对象使用的资源(内存除外)。Disposes of the resources (other than memory) used by the DataView object.

EndInit()

结束在窗体上使用或由另一个组件使用的 DataView 的初始化。Ends the initialization of a DataView that is used on a form or used by another component. 此初始化在运行时发生。The initialization occurs at runtime.

Equals(DataView)

确定指定的 DataView 实例是否可视为相等的实例。Determines whether the specified DataView instances are considered equal.

Equals(Object)

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

(继承自 Object)
Find(Object)

根据指定的排序键值在 DataView 中查找行。Finds a row in the DataView by the specified sort key value.

Find(Object[])

根据指定的排序键值在 DataView 中查找行。Finds a row in the DataView by the specified sort key values.

FindRows(Object)

返回其列与指定的排序键值匹配的 DataRowView 对象数组。Returns an array of DataRowView objects whose columns match the specified sort key value.

FindRows(Object[])

返回其列与指定的排序键值匹配的 DataRowView 对象数组。Returns an array of DataRowView objects whose columns match the specified sort key value.

GetEnumerator()

获取此 DataView 的枚举器。Gets an enumerator for this DataView.

GetHashCode()

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

(继承自 Object)
GetService(Type)

获取 IServiceProvider 的实施者。Gets the implementer of the IServiceProvider.

(继承自 MarshalByValueComponent)
GetType()

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

(继承自 Object)
IndexListChanged(Object, ListChangedEventArgs)

在成功更改 DataView 后发生。Occurs after a DataView has been changed successfully.

MemberwiseClone()

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

(继承自 Object)
OnListChanged(ListChangedEventArgs)

引发 ListChanged 事件。Raises the ListChanged event.

Open()

打开 DataViewOpens a DataView.

Reset()

保留以仅供内部使用。Reserved for internal use only.

ToString()

返回包含 Component 的名称的 String(如果有)。Returns a String containing the name of the Component, if any. 不应重写此方法。This method should not be overridden.

(继承自 MarshalByValueComponent)
ToTable()

基于现有的 DataView 中的行,创建并返回一个新的 DataTableCreates and returns a new DataTable based on rows in an existing DataView.

ToTable(Boolean, String[])

基于现有的 DataView 中的行,创建并返回一个新的 DataTableCreates and returns a new DataTable based on rows in an existing DataView.

ToTable(String)

基于现有的 DataView 中的行,创建并返回一个新的 DataTableCreates and returns a new DataTable based on rows in an existing DataView.

ToTable(String, Boolean, String[])

基于现有的 DataView 中的行,创建并返回一个新的 DataTableCreates and returns a new DataTable based on rows in an existing DataView.

UpdateIndex()

保留以仅供内部使用。Reserved for internal use only.

UpdateIndex(Boolean)

保留以仅供内部使用。Reserved for internal use only.

事件

Disposed

添加事件处理程序以侦听组件上的 Disposed 事件。Adds an event handler to listen to the Disposed event on the component.

(继承自 MarshalByValueComponent)
Initialized

DataView 的初始化完成时发生。Occurs when initialization of the DataView is completed.

ListChanged

更改由 DataView 管理的列表时发生。Occurs when the list managed by the DataView changes.

显式界面实现

IBindingList.AddIndex(PropertyDescriptor)

有关此成员的说明,请参见 AddIndex(PropertyDescriptor)For a description of this member, see AddIndex(PropertyDescriptor).

IBindingList.AddNew()

有关此成员的说明,请参见 AddNew()For a description of this member, see AddNew().

IBindingList.AllowEdit

有关此成员的说明,请参见 AllowEditFor a description of this member, see AllowEdit.

IBindingList.AllowNew

有关此成员的说明,请参见 AllowNewFor a description of this member, see AllowNew.

IBindingList.AllowRemove

有关此成员的说明,请参见 AllowRemoveFor a description of this member, see AllowRemove.

IBindingList.ApplySort(PropertyDescriptor, ListSortDirection)

有关此成员的说明,请参见 ApplySort(PropertyDescriptor, ListSortDirection)For a description of this member, see ApplySort(PropertyDescriptor, ListSortDirection).

IBindingList.Find(PropertyDescriptor, Object)

有关此成员的说明,请参见 Find(PropertyDescriptor, Object)For a description of this member, see Find(PropertyDescriptor, Object).

IBindingList.IsSorted

有关此成员的说明,请参见 IsSortedFor a description of this member, see IsSorted.

IBindingList.RemoveIndex(PropertyDescriptor)

有关此成员的说明,请参见 RemoveIndex(PropertyDescriptor)For a description of this member, see RemoveIndex(PropertyDescriptor).

IBindingList.RemoveSort()

有关此成员的说明,请参见 RemoveSort()For a description of this member, see RemoveSort().

IBindingList.SortDirection

有关此成员的说明,请参见 SortDirectionFor a description of this member, see SortDirection.

IBindingList.SortProperty

有关此成员的说明,请参见 SortPropertyFor a description of this member, see SortProperty.

IBindingList.SupportsChangeNotification

有关此成员的说明,请参见 SupportsChangeNotificationFor a description of this member, see SupportsChangeNotification.

IBindingList.SupportsSearching

有关此成员的说明,请参见 SupportsSearchingFor a description of this member, see SupportsSearching.

IBindingList.SupportsSorting

有关此成员的说明,请参见 SupportsSortingFor a description of this member, see SupportsSorting.

IBindingListView.ApplySort(ListSortDescriptionCollection)

有关此成员的说明,请参见 ApplySort(ListSortDescriptionCollection)For a description of this member, see ApplySort(ListSortDescriptionCollection).

IBindingListView.Filter

有关此成员的说明,请参见 FilterFor a description of this member, see Filter.

IBindingListView.RemoveFilter()

有关此成员的说明,请参见 RemoveFilter()For a description of this member, see RemoveFilter().

IBindingListView.SortDescriptions

有关此成员的说明,请参见 SortDescriptionsFor a description of this member, see SortDescriptions.

IBindingListView.SupportsAdvancedSorting

有关此成员的说明,请参见 SupportsAdvancedSortingFor a description of this member, see SupportsAdvancedSorting.

IBindingListView.SupportsFiltering

有关此成员的说明,请参见 SupportsFilteringFor a description of this member, see SupportsFiltering.

ICollection.IsSynchronized

有关此成员的说明,请参见 IsSynchronizedFor a description of this member, see IsSynchronized.

ICollection.SyncRoot

有关此成员的说明,请参见 SyncRootFor a description of this member, see SyncRoot.

IList.Add(Object)

有关此成员的说明,请参见 Add(Object)For a description of this member, see Add(Object).

IList.Clear()

有关此成员的说明,请参见 Clear()For a description of this member, see Clear().

IList.Contains(Object)

有关此成员的说明,请参见 Contains(Object)For a description of this member, see Contains(Object).

IList.IndexOf(Object)

有关此成员的说明,请参见 IndexOf(Object)For a description of this member, see IndexOf(Object).

IList.Insert(Int32, Object)

有关此成员的说明,请参见 Insert(Int32, Object)For a description of this member, see Insert(Int32, Object).

IList.IsFixedSize

有关此成员的说明,请参见 IsFixedSizeFor a description of this member, see IsFixedSize.

IList.IsReadOnly

有关此成员的说明,请参见 IsReadOnlyFor a description of this member, see IsReadOnly.

IList.Item[Int32]

有关此成员的说明,请参见 Item[Int32]For a description of this member, see Item[Int32].

IList.Remove(Object)

有关此成员的说明,请参见 Remove(Object)For a description of this member, see Remove(Object).

IList.RemoveAt(Int32)

有关此成员的说明,请参见 RemoveAt(Int32)For a description of this member, see RemoveAt(Int32).

ITypedList.GetItemProperties(PropertyDescriptor[])

有关此成员的说明,请参见 GetItemProperties(PropertyDescriptor[])For a description of this member, see GetItemProperties(PropertyDescriptor[]).

ITypedList.GetListName(PropertyDescriptor[])

有关此成员的说明,请参见 GetListName(PropertyDescriptor[])For a description of this member, see GetListName(PropertyDescriptor[]).

扩展方法

Cast<TResult>(IEnumerable)

IEnumerable 的元素强制转换为指定的类型。Casts the elements of an IEnumerable to the specified type.

OfType<TResult>(IEnumerable)

根据指定类型筛选 IEnumerable 的元素。Filters the elements of an IEnumerable based on a specified type.

AsParallel(IEnumerable)

启用查询的并行化。Enables parallelization of a query.

AsQueryable(IEnumerable)

IEnumerable 转换为 IQueryableConverts an IEnumerable to an IQueryable.

适用于

线程安全性

对于多线程读取操作, 此类型是安全的。This type is safe for multithreaded read operations. 必须同步任何写入操作。You must synchronize any write operations.

另请参阅