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 list box, you can simply bind the Customers table in your data set to a DataGrid control.

To illustrate, alter Example 14-1 by deleting the list box from the form you created in the previous example 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 ...

Get Programming C#, Second 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.