MSDN Documentation

DataViews

The DataView class in ADO.NET provides a way to sort and filter DataTable data. It acts as a programmable view of the data in a DataTable, allowing you to present the data in different ways without modifying the underlying DataTable itself.

Key Features of DataView

Creating and Using a DataView

To create a DataView, you instantiate the DataView class and pass the DataTable you want to view to its constructor. You can then set properties like Sort and RowFilter to configure the view.

Example: Sorting and Filtering

Let's assume you have a DataTable named productsTable with columns like ProductID, ProductName, and UnitPrice.


// Assume productsTable is already populated with data

// Create a DataView from the DataTable
DataView dataView = new DataView(productsTable);

// Sort the DataView by ProductName in ascending order
dataView.Sort = "ProductName ASC";

// Filter the DataView to show products with UnitPrice greater than 50
dataView.RowFilter = "UnitPrice > 50";

// Now, iterate through the filtered and sorted data
foreach (DataRowView rowView in dataView)
{
    Console.WriteLine($"Product: {rowView["ProductName"]}, Price: {rowView["UnitPrice"]}");
}
            

Key Properties

RowFilter Syntax

The RowFilter property uses an expression language to define filtering criteria. Here are some examples:

Sort Syntax

The Sort property uses an expression language to define sorting order. Here are some examples:

Note on DataViewManager

The DataViewManager class is used to create DataView objects that can be bound to data-bound controls. It manages the creation of DataView objects for different DataTable objects within a DataSet.

Conclusion

DataView is a powerful tool for manipulating and presenting data from a DataTable in ADO.NET. Its ability to sort, filter, and reflect changes dynamically makes it indispensable for data-driven applications.