Working with Data-Bound Controls

ADO.NET provides good support for “data-bound” objects; that is, objects that can be tied to a particular data set, such as one retrieved from a database by ADO.NET.

A simple example of a data-bound control is the DataGrid control provided with both Windows Forms and Web Forms.

Populating a DataGrid

In its simplest use, a DataGrid is easy to implement. Once again, first create a DataSet and then fill it from the Customers table of the Northwind database, but this time, rather than iterating through the rows of the data set and writing the output to a listbox, you can simply bind the Customers table in your data set to a DataGrid control.

To illustrate, alter Example 14-1 by deleting the listbox from the form you created and replace it with a DataGrid. The default name provided by the Visual Studio design tool is DataGrid1, but let’s change it to CustomerDataGrid. After the data set is created and filled, bind the DataGrid through its DataSource property:

CustomerDataGrid.DataSource=
    DataSet.Tables["Customers"].DefaultView;

Example 14-3 provides the complete source code for this example.

Example 14-3. Using a DataGrid control

using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using System.Data.SqlClient; namespace ProgrammingCSharpWindows.Form { public class ADOForm3 : System.Windows.Forms.Form { private System.ComponentModel.Container components; private System.Windows.Forms.DataGrid ...

Get Programming C#, Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.