Creating a Data Grid

You are now ready to return to the data grid examples from Chapter 10 and recode them by accessing the database. You will remember that in Example 10-7 and Example 10-8, you created a simple data grid, and then populated it with data from an ArrayList object. You can re-create that now using ADO.NET to get bug data from the database.

To start, create a new C# project, SimpleADODataGrid. Drag a DataGrid control onto the form, Visual Studio will name it DataGrid1. Accept all the default attributes as offered.

In the code-behind page’s Page_Load method, you get the Bugs table from the database, just as you did in Example 11-3:

string connectionString = 
   "server=YourServer; uid=sa; " +
   "pwd=YourPassword; database=ProgASPDotNetBugs";

// get records from the Bugs table
string commandString = 
   "Select BugID, Description from Bugs";

// create the dataset  command object 
// and the DataSet
SqlDataAdapter dataAdapter = 
   new SqlDataAdapter(
   commandString, connectionString);

DataSet dataSet = new DataSet(  );

// fill the dataset  object
dataAdapter.Fill(dataSet,"Bugs");

// Get the one table from the DataSet
DataTable dataTable = dataSet.Tables[0];

This time, however, you’ll bind to the data grid rather than to a list box. To do so, you set the DataGrid control’s DataSource property to dataTable, the DataTable object you get from the dataset, and then call DataBind on the data grid:

DataGrid1.DataSource=dataTable;
DataGrid1.DataBind(  );

When you run the page, hey! presto! the data grid ...

Get Programming ASP.NET, 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.