DataView DataView DataView DataView Class

Definition

Represents a databindable, customized view of a DataTable for sorting, filtering, searching, editing, and navigation. The DataView does not store data, but instead represents a connected view of its corresponding DataTable. Changes to the DataView’s data will affect the DataTable. Changes to the DataTable’s data will affect all DataViews associated with it.

public ref class DataView : System::ComponentModel::MarshalByValueComponent, System::Collections::IList, System::ComponentModel::IBindingList, System::ComponentModel::IBindingListView, System::ComponentModel::ISupportInitialize, System::ComponentModel::ISupportInitializeNotification, System::ComponentModel::ITypedList
public class DataView : System.ComponentModel.MarshalByValueComponent, System.Collections.IList, System.ComponentModel.IBindingList, System.ComponentModel.IBindingListView, System.ComponentModel.ISupportInitialize, 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 IBindingList, IBindingListView, IList, ISupportInitialize, ISupportInitializeNotification, ITypedList
Inheritance
Implements

Examples

The following example creates a single DataTable with one column and five rows. 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 DataTable = New DataTable("table")
    Dim colItem As DataColumn = 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 DataView = New DataView(table)
    Dim secondView As DataView = 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

The following example creates a DataView of online orders ordered by total due from a LINQ 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

Remarks

A major function of the DataView is to allow for data binding on both Windows Forms and Web Forms.

Additionally, a DataView can be customized to present a subset of data from the DataTable. This capability lets you have two controls bound to the same DataTable, but that show different versions of the data. 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. The DataTable also has a DefaultView property. This returns the default DataView for the table. For example, if you want to create a custom view on the table, set the RowFilter on the DataView returned by the DefaultView.

To create a filtered and sorted view of data, set the RowFilter and Sort properties. Then, use the Item[Int32] property to return a single DataRowView.

You can also add and delete from the set of rows using the AddNew and Delete methods. When you use those methods, the RowStateFilter property can set to specify that only deleted rows or new rows be displayed by the DataView.

Note

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 DataSet allows developers to create complex, powerful queries over a DataSet by using LINQ. A LINQ to DataSet query returns an enumeration of DataRow objects, however, which is not easily used in a binding scenario. DataView can be created from a LINQ to DataSet query and takes on the filtering and sorting characteristics of that query. LINQ to DataSet extends the functionality of the DataView by providing LINQ expression-based filtering and sorting, which allows for much more complex and powerful filtering and sorting operations than string-based filtering and sorting. See Data Binding and LINQ to DataSet for more information.

Constructors

DataView() DataView() DataView() DataView()

Initializes a new instance of the DataView class.

DataView(DataTable) DataView(DataTable) DataView(DataTable) DataView(DataTable)

Initializes a new instance of the DataView class with the specified DataTable.

DataView(DataTable, String, String, DataViewRowState) DataView(DataTable, String, String, DataViewRowState) DataView(DataTable, String, String, DataViewRowState) DataView(DataTable, String, String, DataViewRowState)

Initializes a new instance of the DataView class with the specified DataTable, RowFilter, Sort, and DataViewRowState.

Properties

AllowDelete AllowDelete AllowDelete AllowDelete

Sets or gets a value that indicates whether deletes are allowed.

AllowEdit AllowEdit AllowEdit AllowEdit

Gets or sets a value that indicates whether edits are allowed.

AllowNew AllowNew AllowNew AllowNew

Gets or sets a value that indicates whether the new rows can be added by using the AddNew() method.

ApplyDefaultSort ApplyDefaultSort ApplyDefaultSort ApplyDefaultSort

Gets or sets a value that indicates whether to use the default sort. The default sort is (ascending) by all primary keys as specified by PrimaryKey.

Container Container Container Container

Gets the container for the component.

(Inherited from MarshalByValueComponent)
Count Count Count Count

Gets the number of records in the DataView after RowFilter and RowStateFilter have been applied.

DataViewManager DataViewManager DataViewManager DataViewManager

Gets the DataViewManager associated with this view.

DesignMode DesignMode DesignMode DesignMode

Gets a value indicating whether the component is currently in design mode.

(Inherited from MarshalByValueComponent)
Events Events Events Events

Gets the list of event handlers that are attached to this component.

(Inherited from MarshalByValueComponent)
IsInitialized IsInitialized IsInitialized IsInitialized

Gets a value that indicates whether the component is initialized.

IsOpen IsOpen IsOpen IsOpen

Gets a value that indicates whether the data source is currently open and projecting views of data on the DataTable.

Item[Int32] Item[Int32] Item[Int32] Item[Int32]

Gets a row of data from a specified table.

RowFilter RowFilter RowFilter RowFilter

Gets or sets the expression used to filter which rows are viewed in the DataView.

RowStateFilter RowStateFilter RowStateFilter RowStateFilter

Gets or sets the row state filter used in the DataView.

Site Site Site Site

Gets or sets the site of the component.

(Inherited from MarshalByValueComponent)
Sort Sort Sort Sort

Gets or sets the sort column or columns, and sort order for the DataView.

Table Table Table Table

Gets or sets the source DataTable.

Methods

AddNew() AddNew() AddNew() AddNew()

Adds a new row to the DataView.

BeginInit() BeginInit() BeginInit() BeginInit()

Starts the initialization of a DataView that is used on a form or used by another component. The initialization occurs at runtime.

Close() Close() Close() Close()

Closes the DataView.

ColumnCollectionChanged(Object, CollectionChangeEventArgs) ColumnCollectionChanged(Object, CollectionChangeEventArgs) ColumnCollectionChanged(Object, CollectionChangeEventArgs) ColumnCollectionChanged(Object, CollectionChangeEventArgs)

Occurs after a DataColumnCollection has been changed successfully.

CopyTo(Array, Int32) CopyTo(Array, Int32) CopyTo(Array, Int32) CopyTo(Array, Int32)

Copies items into an array. Only for Web Forms Interfaces.

Delete(Int32) Delete(Int32) Delete(Int32) Delete(Int32)

Deletes a row at the specified index.

Dispose() Dispose() Dispose() Dispose()

Releases all resources used by the MarshalByValueComponent.

(Inherited from MarshalByValueComponent)
Dispose(Boolean) Dispose(Boolean) Dispose(Boolean) Dispose(Boolean)

Disposes of the resources (other than memory) used by the DataView object.

EndInit() EndInit() EndInit() EndInit()

Ends the initialization of a DataView that is used on a form or used by another component. The initialization occurs at runtime.

Equals(DataView) Equals(DataView) Equals(DataView) Equals(DataView)

Determines whether the specified DataView instances are considered equal.

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

Determines whether the specified object is equal to the current object.

(Inherited from Object)
Find(Object) Find(Object) Find(Object) Find(Object)

Finds a row in the DataView by the specified sort key value.

Find(Object[]) Find(Object[]) Find(Object[]) Find(Object[])

Finds a row in the DataView by the specified sort key values.

FindRows(Object) FindRows(Object) FindRows(Object) FindRows(Object)

Returns an array of DataRowView objects whose columns match the specified sort key value.

FindRows(Object[]) FindRows(Object[]) FindRows(Object[]) FindRows(Object[])

Returns an array of DataRowView objects whose columns match the specified sort key value.

GetEnumerator() GetEnumerator() GetEnumerator() GetEnumerator()

Gets an enumerator for this DataView.

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

Serves as the default hash function.

(Inherited from Object)
GetService(Type) GetService(Type) GetService(Type) GetService(Type)

Gets the implementer of the IServiceProvider.

(Inherited from MarshalByValueComponent)
GetType() GetType() GetType() GetType()

Gets the Type of the current instance.

(Inherited from Object)
IndexListChanged(Object, ListChangedEventArgs) IndexListChanged(Object, ListChangedEventArgs) IndexListChanged(Object, ListChangedEventArgs) IndexListChanged(Object, ListChangedEventArgs)

Occurs after a DataView has been changed successfully.

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

Creates a shallow copy of the current Object.

(Inherited from Object)
OnListChanged(ListChangedEventArgs) OnListChanged(ListChangedEventArgs) OnListChanged(ListChangedEventArgs) OnListChanged(ListChangedEventArgs)

Raises the ListChanged event.

Open() Open() Open() Open()

Opens a DataView.

Reset() Reset() Reset() Reset()

Reserved for internal use only.

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

Returns a String containing the name of the Component, if any. This method should not be overridden.

(Inherited from MarshalByValueComponent)
ToTable() ToTable() ToTable() ToTable()

Creates and returns a new DataTable based on rows in an existing DataView.

ToTable(Boolean, String[]) ToTable(Boolean, String[]) ToTable(Boolean, String[]) ToTable(Boolean, String[])

Creates and returns a new DataTable based on rows in an existing DataView.

ToTable(String) ToTable(String) ToTable(String) ToTable(String)

Creates and returns a new DataTable based on rows in an existing DataView.

ToTable(String, Boolean, String[]) ToTable(String, Boolean, String[]) ToTable(String, Boolean, String[]) ToTable(String, Boolean, String[])

Creates and returns a new DataTable based on rows in an existing DataView.

UpdateIndex() UpdateIndex() UpdateIndex() UpdateIndex()

Reserved for internal use only.

UpdateIndex(Boolean) UpdateIndex(Boolean) UpdateIndex(Boolean) UpdateIndex(Boolean)

Reserved for internal use only.

Events

Disposed Disposed Disposed Disposed

Adds an event handler to listen to the Disposed event on the component.

(Inherited from MarshalByValueComponent)
Initialized Initialized Initialized Initialized

Occurs when initialization of the DataView is completed.

ListChanged ListChanged ListChanged ListChanged

Occurs when the list managed by the DataView changes.

Explicit Interface Implementations

IBindingList.AddIndex(PropertyDescriptor) IBindingList.AddIndex(PropertyDescriptor) IBindingList.AddIndex(PropertyDescriptor) IBindingList.AddIndex(PropertyDescriptor)

For a description of this member, see AddIndex(PropertyDescriptor).

IBindingList.AddNew() IBindingList.AddNew() IBindingList.AddNew() IBindingList.AddNew()

For a description of this member, see AddNew().

IBindingList.AllowEdit IBindingList.AllowEdit IBindingList.AllowEdit IBindingList.AllowEdit

For a description of this member, see AllowEdit.

IBindingList.AllowNew IBindingList.AllowNew IBindingList.AllowNew IBindingList.AllowNew

For a description of this member, see AllowNew.

IBindingList.AllowRemove IBindingList.AllowRemove IBindingList.AllowRemove IBindingList.AllowRemove

For a description of this member, see AllowRemove.

IBindingList.ApplySort(PropertyDescriptor, ListSortDirection) IBindingList.ApplySort(PropertyDescriptor, ListSortDirection) IBindingList.ApplySort(PropertyDescriptor, ListSortDirection) IBindingList.ApplySort(PropertyDescriptor, ListSortDirection)

For a description of this member, see ApplySort(PropertyDescriptor, ListSortDirection).

IBindingList.Find(PropertyDescriptor, Object) IBindingList.Find(PropertyDescriptor, Object) IBindingList.Find(PropertyDescriptor, Object) IBindingList.Find(PropertyDescriptor, Object)

For a description of this member, see Find(PropertyDescriptor, Object).

IBindingList.IsSorted IBindingList.IsSorted IBindingList.IsSorted IBindingList.IsSorted

For a description of this member, see IsSorted.

IBindingList.RemoveIndex(PropertyDescriptor) IBindingList.RemoveIndex(PropertyDescriptor) IBindingList.RemoveIndex(PropertyDescriptor) IBindingList.RemoveIndex(PropertyDescriptor)

For a description of this member, see RemoveIndex(PropertyDescriptor).

IBindingList.RemoveSort() IBindingList.RemoveSort() IBindingList.RemoveSort() IBindingList.RemoveSort()

For a description of this member, see RemoveSort().

IBindingList.SortDirection IBindingList.SortDirection IBindingList.SortDirection IBindingList.SortDirection

For a description of this member, see SortDirection.

IBindingList.SortProperty IBindingList.SortProperty IBindingList.SortProperty IBindingList.SortProperty

For a description of this member, see SortProperty.

IBindingList.SupportsChangeNotification IBindingList.SupportsChangeNotification IBindingList.SupportsChangeNotification IBindingList.SupportsChangeNotification

For a description of this member, see SupportsChangeNotification.

IBindingList.SupportsSearching IBindingList.SupportsSearching IBindingList.SupportsSearching IBindingList.SupportsSearching

For a description of this member, see SupportsSearching.

IBindingList.SupportsSorting IBindingList.SupportsSorting IBindingList.SupportsSorting IBindingList.SupportsSorting

For a description of this member, see SupportsSorting.

IBindingListView.ApplySort(ListSortDescriptionCollection) IBindingListView.ApplySort(ListSortDescriptionCollection) IBindingListView.ApplySort(ListSortDescriptionCollection) IBindingListView.ApplySort(ListSortDescriptionCollection)

For a description of this member, see ApplySort(ListSortDescriptionCollection).

IBindingListView.Filter IBindingListView.Filter IBindingListView.Filter IBindingListView.Filter

For a description of this member, see Filter.

IBindingListView.RemoveFilter() IBindingListView.RemoveFilter() IBindingListView.RemoveFilter() IBindingListView.RemoveFilter()

For a description of this member, see RemoveFilter().

IBindingListView.SortDescriptions IBindingListView.SortDescriptions IBindingListView.SortDescriptions IBindingListView.SortDescriptions

For a description of this member, see SortDescriptions.

IBindingListView.SupportsAdvancedSorting IBindingListView.SupportsAdvancedSorting IBindingListView.SupportsAdvancedSorting IBindingListView.SupportsAdvancedSorting

For a description of this member, see SupportsAdvancedSorting.

IBindingListView.SupportsFiltering IBindingListView.SupportsFiltering IBindingListView.SupportsFiltering IBindingListView.SupportsFiltering

For a description of this member, see SupportsFiltering.

ICollection.IsSynchronized ICollection.IsSynchronized ICollection.IsSynchronized ICollection.IsSynchronized

For a description of this member, see IsSynchronized.

ICollection.SyncRoot ICollection.SyncRoot ICollection.SyncRoot ICollection.SyncRoot

For a description of this member, see SyncRoot.

IList.Add(Object) IList.Add(Object) IList.Add(Object) IList.Add(Object)

For a description of this member, see Add(Object).

IList.Clear() IList.Clear() IList.Clear() IList.Clear()

For a description of this member, see Clear().

IList.Contains(Object) IList.Contains(Object) IList.Contains(Object) IList.Contains(Object)

For a description of this member, see Contains(Object).

IList.IndexOf(Object) IList.IndexOf(Object) IList.IndexOf(Object) IList.IndexOf(Object)

For a description of this member, see IndexOf(Object).

IList.Insert(Int32, Object) IList.Insert(Int32, Object) IList.Insert(Int32, Object) IList.Insert(Int32, Object)

For a description of this member, see Insert(Int32, Object).

IList.IsFixedSize IList.IsFixedSize IList.IsFixedSize IList.IsFixedSize

For a description of this member, see IsFixedSize.

IList.IsReadOnly IList.IsReadOnly IList.IsReadOnly IList.IsReadOnly

For a description of this member, see IsReadOnly.

IList.Item[Int32] IList.Item[Int32] IList.Item[Int32] IList.Item[Int32]

For a description of this member, see Item[Int32].

IList.Remove(Object) IList.Remove(Object) IList.Remove(Object) IList.Remove(Object)

For a description of this member, see Remove(Object).

IList.RemoveAt(Int32) IList.RemoveAt(Int32) IList.RemoveAt(Int32) IList.RemoveAt(Int32)

For a description of this member, see RemoveAt(Int32).

ITypedList.GetItemProperties(PropertyDescriptor[]) ITypedList.GetItemProperties(PropertyDescriptor[]) ITypedList.GetItemProperties(PropertyDescriptor[]) ITypedList.GetItemProperties(PropertyDescriptor[])

For a description of this member, see GetItemProperties(PropertyDescriptor[]).

ITypedList.GetListName(PropertyDescriptor[]) ITypedList.GetListName(PropertyDescriptor[]) ITypedList.GetListName(PropertyDescriptor[]) ITypedList.GetListName(PropertyDescriptor[])

For a description of this member, see GetListName(PropertyDescriptor[]).

Extension Methods

Cast<TResult>(IEnumerable) Cast<TResult>(IEnumerable) Cast<TResult>(IEnumerable) Cast<TResult>(IEnumerable)

Casts the elements of an IEnumerable to the specified type.

OfType<TResult>(IEnumerable) OfType<TResult>(IEnumerable) OfType<TResult>(IEnumerable) OfType<TResult>(IEnumerable)

Filters the elements of an IEnumerable based on a specified type.

AsParallel(IEnumerable) AsParallel(IEnumerable) AsParallel(IEnumerable) AsParallel(IEnumerable)

Enables parallelization of a query.

AsQueryable(IEnumerable) AsQueryable(IEnumerable) AsQueryable(IEnumerable) AsQueryable(IEnumerable)

Converts an IEnumerable to an IQueryable.

Applies to

Thread Safety

This type is safe for multithreaded read operations. You must synchronize any write operations.

See Also