Home   Cover Cover Cover Cover

A Simple DataGrid

From Section 6.4.11 of the book

This examples displays the employee records of a database in a DataGrid control. The aspx page in which the DataGrid is declared look like this:

<%@ Page Language="C#" Inherits="BasePage" Src="DataGrid.aspx.cs" %>
    <form OnInit="PageInit" Runat="server">
      <asp:DataGrid ID="grid" OnLoad="GridLoad" Runat="server" />

The script code is stored in the following code-behind file:

using System;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Web.UI;
using System.Web.UI.WebControls;

public class BasePage : Page {
  protected DataGrid grid;
  DataView dataView;
  public void PageInit(object sender, EventArgs e) {
    DataSet ds = new DataSet();
    SqlConnection con = new SqlConnection("data source=\\NETSDK; " +
      "initial catalog=Northwind; user id=sa; password=; Trusted_Connection=true");
    string sqlString = "SELECT EmployeeID, FirstName, LastName FROM Employees";
    SqlDataAdapter adapter = new SqlDataAdapter(sqlString, con);
    adapter.Fill(ds, "Employees");
    if (ds.HasErrors) ds.RejectChanges(); else ds.AcceptChanges();
    dataView = ds.Tables["Employees"].DefaultView;
  public void GridLoad(object sender, EventArgs e) {
    grid.HeaderStyle.Font.Bold = true;
    grid.AlternatingItemStyle.BackColor = System.Drawing.Color.LightGray;
    grid.DataSource = dataView;

Try it