Windows Forms: Data Grid Sorting and Filtering

This sample shows how you can retrieve data from the database, and display that
data in a datagrid.

Featured Highlights

ADO.NET is used to retrieve the information from SQL Server. The data is loaded into
a DataSet, and the grid is populated by binding to the DataSet. ADO.NET is also used
to filter the data. When the user clicks the Filter button, a DataView is used to
exclude some of the rows. You can also re-sort the data simply by clicking any column
headings in the DataGrid.

The controls on this form utilize anchoring so that the form resizes intelligently
without the developer having to write any code.

Tooltips are used on the TextBox, and the Load Data buttons to provide additional
guidance to the user.

Validation is done in the filtering event procedure. If the user enters a criteria
that doesn't match any rows, the user is notified.

Debug.Assert is used to perform a sanity check. This "defensive coding" can prevent
bugs that would be easily introduced later. For detail on how to test the Debug.Assert,
see the notes section.

Debug.Assert is used in the filter event procedure to insure that the DataSet contains
data before attempting to filter the results. To see this in action, do the following:

1. Change the Enabled property of btnFilter from false to true.
2. Press F5 to start the application.
3. Click "Filter" without clicking "Load Data".

Debug.Assert only operates when compiling in debug mode, so you don't have to worry about
it showing errors or wasting processor cycles in released code.

1. On the Visual Studio toolbar, change the Solution Configurations drop down from
"Debug" to "Release"
2. Press F5
3. Click "Filter" without clicking "Load Data".

Requirements

Requires the release version of Visual Studio .NET Professional (or greater)
and access to the Northwind database residing in SQL Server or the Microsoft
Data Engine (MSDE). To install MSDE, do the following:

1. Open the Start menu, then click Programs, the click Microsoft .NET Framework
SDK, and then click Samples and Quickstart Tutorials.

2. Click "Step 1: Install the .NET Framework Samples Database".

3. Open a command window, and CD to <FrameworkSDK>\Samples\Setup
This is typically :
C:\Program Files\Microsoft Visual Studio .NET\FrameworkSDK\Samples\Setup

4. Type: osql -E -S (local)\NetSDK -i InstNwnd.sql

Running the Sample

Simply Press F5.

See also

DataGrid  Working with the DataGrid