Filtering for Null Values


You want to filter a DataView for rows that have null values.


Use the IS NULL clause with the RowFilters property of the DataView .

The sample code contains two event handlers:


Sets up the sample by creating a DataTable containing the Orders table from the Northwind sample database. The default view of the table is bound to the data grid on the form.

Filter Button.Click

Toggles on and off the filter on the data view that selects only rows with a null ShipRegion.

The C# code is shown in Example 3-12.

Example 3-12. File: FilterNullValuesForm.cs

// Namespaces, variables, and constants
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
// Table name constants
private const String ORDERS_TABLE = "Orders";

// Field name constants
private const String SHIPREGION_FIELD = "ShipRegion";

// . . . 

private void FilterNullValuesForm_Load(object sender, System.EventArgs e)
 // Create and fill the Orders table.
 DataTable dt = new DataTable(ORDERS_TABLE);
 SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Orders",

 // Bind the default view to the grid.
 dataGrid.DataSource = dt.DefaultView; 

private void filterButton_Click(object sender, System.EventArgs e)
 String filter = SHIPREGION_FIELD + " IS NULL";

 DataView dv = (DataView)dataGrid.DataSource;

 if(filterButton.Text == "Apply Filter")
 // Apply the filter.
 dv.RowFilter = filter;
 dataGrid.CaptionText =
 "Orders table: filtered for null ShipRegion field.";
 filterButton.Text = "Remove Filter";
 // Remove the filter.
 dv.RowFilter = "";
 dataGrid.CaptionText = "Orders table: no filter.";
 filterButton.Text = "Apply Filter";


Every DataTable has a default DataView associated with it that can filter a table for records meeting specific criteria. In the solution, the RowFilter property of the DefaultView is filtered for rows containing a null ShipRegion field. The result of applying the filter is immediately reflected in any controls bound to the DataView object in addition to the any operations performed on the records within the DataView .

Alternatively, you can use the Select( ) method on the DataTable underlying the DataView to retrieve an array of DataRow objects containing only rows with the null ShipRegion using the same filter expression.

Connecting to Data

Retrieving and Managing Data

Searching and Analyzing Data

Adding and Modifying Data

Copying and Transferring Data

Maintaining Database Integrity

Binding Data to .NET User Interfaces

Working with XML

Optimizing .NET Data Access

Enumerating and Maintaining Database Objects

Appendix A. Converting from C# to VB Syntax

ADO. NET Cookbook
ADO.NET 3.5 Cookbook (Cookbooks (OReilly))
ISBN: 0596101406
EAN: 2147483647
Year: 2002
Pages: 222
Authors: Bill Hamilton © 2008-2020.
If you may any questions please contact us: