Home   Cover Cover Cover Cover

An Editable DataGrid

From Section 6.4.11 of the book

This is a more advanced example for the usage of a DataGrid control. The grid is filled with employee records from a database. Every row of the grid contains buttons to delete or select the specific row.

The DataGrid is declared in the following aspx file, which also specifies the layout and the look of the individual grid columns.

<%@ Page Language="C#" Inherits="BasePage" src="DataGrid2.aspx.cs" %>
    <form onLoad="PageLoad" Runat="server">
      <asp:DataGrid ID="grid" Runat="server"
        <HeaderStyle BackColor="#aaaadd"/>
          <asp:BoundColumn HeaderText="ID" DataField="EmployeeID">
            <ItemStyle HorizontalAlign="Right" />
          <asp:BoundColumn HeaderText="First Name" DataField="FirstName" />
          <asp:BoundColumn HeaderText="Last Name" DataField="LastName" />
          <asp:ButtonColumn ButtonType="LinkButton" Text="delete" CommandName="Delete" />
          <asp:ButtonColumn ButtonType="LinkButton" Text="select" CommandName="Select" />
      <asp:Label ID="label" 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;
  protected Label label;
  DataView dataView;
  public void PageLoad(object sender, EventArgs e) {
    DataSet ds;
    if (!IsPostBack) {
      ds = new DataSet();
      SqlConnection con = new SqlConnection("data source=\\NETSDK; " +
        "initial catalog=Northwind; user id=sa; password=; Trusted_Connection=true");
      string cmd = "SELECT EmployeeID, FirstName, LastName FROM Employees";
      SqlDataAdapter adapter = new SqlDataAdapter(cmd, con);
      adapter.Fill(ds, "Employees");
      if (ds.HasErrors) ds.RejectChanges(); else ds.AcceptChanges();
      Session["Data"] = ds;
    } else
      ds = (DataSet)Session["Data"];
    dataView = ds.Tables["Employees"].DefaultView;
    grid.DataSource = dataView;
  public void DeleteRow(object sender, DataGridCommandEventArgs e) {
    dataView.RowFilter = "EmployeeID='" + e.Item.Cells[0].Text + "'";
    if (dataView.Count > 0) dataView.Delete(0);  // deletes data only in DataView object
    dataView.RowFilter = "";                    // but not in the database
    grid.DataSource = dataView;
  public void SelectRow(object sender, EventArgs e) {
    grid.SelectedItemStyle.BackColor = System.Drawing.Color.Gray;
    label.Text = grid.SelectedItem.Cells[1].Text + " " + 

Try it