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:

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

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

DataGrid.aspx.cs
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=127.0.0.1\\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;
    grid.DataBind();
  }
  
}

Try it

   http://dotnet.jku.at/book/samples/6/DataGrid.aspx