DataView Objects

The DataView object provides a way to view and interact with data stored in a DataTable. It acts as a dynamic view on the DataTable, allowing you to filter, sort, and navigate through the data without modifying the underlying DataTable itself. This is particularly useful for data binding scenarios and for presenting specific subsets of data to the user.

Key Features of DataView

Creating and Using a DataView

To create a DataView, you typically instantiate it with a DataTable. You can then configure its properties for filtering and sorting.


using System;
using System.Data;

// Assume 'dataTable' is an existing DataTable object populated with data.
DataTable dataTable = new DataTable("Products");
dataTable.Columns.Add("ProductID", typeof(int));
dataTable.Columns.Add("ProductName", typeof(string));
dataTable.Columns.Add("Category", typeof(string));
dataTable.Columns.Add("Price", typeof(decimal));

dataTable.Rows.Add(1, "Laptop", "Electronics", 1200.00m);
dataTable.Rows.Add(2, "Mouse", "Electronics", 25.00m);
dataTable.Rows.Add(3, "Keyboard", "Electronics", 75.00m);
dataTable.Rows.Add(4, "Desk Chair", "Furniture", 150.00m);
dataTable.Rows.Add(5, "Monitor", "Electronics", 300.00m);

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

// Set a filter expression to show only electronics
dataView.RowFilter = "Category = 'Electronics'";

// Set a sort order
dataView.Sort = "Price DESC";

// Iterate through the filtered and sorted data
Console.WriteLine("Filtered and Sorted Electronics Products:");
foreach (DataRowView rowView in dataView)
{
    Console.WriteLine($"  {rowView["ProductName"]} - ${rowView["Price"]}");
}
            

DataView Properties

The following are some of the most commonly used properties of the DataView object:

Property Description
Table Gets or sets the DataTable associated with the DataView.
RowFilter Gets or sets the expression used to filter the rows in the DataView.
Sort Gets or sets the column or columns to sort the DataView by.
Count Gets the number of rows in the DataView after filtering.
Item[] Gets a DataRowView object at the specified index in the DataView.

DataViewRowState

When working with DataView, you can also specify which row states to include. This is done using the DataViewRowState enumeration, which can be combined with the RowFilter. Common states include:


// Example: Show only modified rows
dataView.RowStateFilter = DataViewRowState.ModifiedCurrent;
            

Conclusion

The DataView object is a powerful tool for manipulating and presenting data from a DataTable. Its ability to filter, sort, and dynamically update makes it an essential component for building data-driven applications in ADO.NET.