Accessing Data Through a DataView

A DataView isn’t just for data binding. You can also use it when making programmatic changes. For example, you might create a DataView that contains rows that match certain criteria and then apply a global change to these rows. For example, the following code creates a view that includes all rows with a null value in the Country field and then deletes them:

// Find all the rows where a Country isn't specified.

DataView view = new DataView(ds.Tables["Customers"]);

view.RowFilter = "Country IS NULL";

// Delete these rows.

foreach (DataRowView row in view)




// Display the results.

dataGrid1.DataSource = ds.Tables["Customers"].DefaultView;

This example uses the indexer for the DataView, which accesses the collection of DataRowView objects. Each DataRowView represents a single row from the original DataTable. The DataRowView provides most of the same features as the underlying DataRow object, including the ability to begin and end editing, access values using the field name, and delete the row. You can also access the underlying DataRow directly through the DataRowView.Row property.

Searching a DataView

Once you have defined a sort order for a DataView, either by setting the RowFilter or the ApplyDefaultSort properties, you can use criteria to search for rows. The DataView provides two methods for this task: Find( ) and FindRows( ) .

For example, if you have a sort defined on the ContactName column of the Customers table, you can use ...

Get ADO.NET in a Nutshell now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.