Insert a Row Within an ASP.NET DataGrid...

Use the footer of a DataGrid to allow insertion of a new row.


By: John Kilgo Date: January 31, 2004 Download the code. Printer Friendly Version

In a previous dotnetjohn article we showed how to insert a row in an ASP.NET Datagrid using a form field outside the datagrid. This article will demonstrate a way to use the footer of the grid as a container for the insertable data.

There will not be too much explanation in this article as the code and grid layout should be fairly simple to understand. First the .aspx page (DGInsert.aspx). I've split the code display into two parts to make it a little easier to explain. The first part of the aspx page is shown below. In the datagrid layout notice that we have set ShowFooter to True and AutoGenerateColumns to False. We've also turned on numeric paging for the grid.

<%@ Page Language="vb" AutoEventWireup="false" Codebehind="DGInsert.aspx.vb" Inherits="DotNetJohn.DGInsert"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>DGInsert</title>
<meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1">
<meta name="CODE_LANGUAGE" content="Visual Basic .NET 7.1">
<meta name=vs_defaultClientScript content="JavaScript">
<meta name=vs_targetSchema content="http://schemas.microsoft.com/intellisense/ie5">
</head>
<body MS_POSITIONING="GridLayout">
<h3>Shipper Code Maintenance</h3>
<form id="Form1" method="post" runat="server">
<asp:DataGrid id="DataGrid1"
              runat="server"
              BorderColor="Red"
              BorderStyle="Solid"
              BorderWidth="1px"
              BackColor="White"
              CellPadding="4"
              ShowFooter="True"
              AutoGenerateColumns="False"
              AllowPaging="True"
              OnPageIndexChanged="ChangePage">
  <HeaderStyle Font-Bold="True" ForeColor="Navy" BackColor="lightyellow"></HeaderStyle>
  <ItemStyle ForeColor="Navy" BackColor="White"></ItemStyle>
  <FooterStyle ForeColor="Navy" BackColor="lightyellow"></FooterStyle>
  <PagerStyle Mode="NumericPages" HorizontalAlign="Center" ForeColor="Navy" BackColor="LightYellow"></PagerStyle>

The second half of the aspx code is shown below. This is where we set up the footer to display a link button to handle the inserted data as well as the textbox to hold the insertable data. In this example we have only two columns to display (ShipperID and CompanyName), with only the CompanyName column to hold insertable data. If you have more than one column to insert, you would repeat the second TemplateColumn as many times as you need, changing the HeaderText, DataItem, and TextBox id as appropriate for each column.

  <Columns>
    <asp:TemplateColumn HeaderText="ID">
      <ItemTemplate>
        <asp:Label id="Label1" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.ShipperID") %>'>
        </asp:Label>
      </ItemTemplate>
      <FooterTemplate>
        <asp:LinkButton id="LinkButton1" runat="server" ForeColor="Navy" CommandName="Insert">Insert</asp:LinkButton>
      </FooterTemplate>
    </asp:TemplateColumn>
    <asp:TemplateColumn HeaderText="Shipper">
      <ItemTemplate>
        <asp:Label id="Label2" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.CompanyName") %>'>
        </asp:Label>
      </ItemTemplate>
      <FooterTemplate>
        <asp:TextBox id="txtCompanyName" runat="server"></asp:TextBox>
      </FooterTemplate>
    </asp:TemplateColumn>
  </Columns>
</asp:DataGrid>
</form>
</body>
</html>

All that remains now is the codebehind page to present the data and to allow for the insertion of new data from the footer of the datagrid. The codebehind page will also be shown in two parts for ease of explanation. This first section of code just gets the data and binds it to the datagrid control.
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration

Public Class DGInsert
  Inherits System.Web.UI.Page

  Protected WithEvents DataGrid1 As System.Web.UI.WebControls.DataGrid

  '-- Web Form Designer Generated Code Omitted --

  Dim sqlConn As SqlConnection
  Dim sqlCmd As SqlCommand
  Dim da As SqlDataAdapter
  Dim ds As DataSet

  Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    If Not Page.IsPostBack Then
      BindGrid()
    End If
  End Sub

  Sub BindGrid()
    Try
      sqlConn = New SqlConnection(ConfigurationSettings.AppSettings("ConnectionString"))
      Dim strSQL As String = "SELECT ShipperID, CompanyName FROM Shippers ORDER BY CompanyName"
      Dim da As New SqlDataAdapter(strSQL, sqlConn)
      Dim ds As New DataSet()
      da.Fill(ds)
      DataGrid1.DataSource = ds
      DataGrid1.DataBind()
    Catch ex As SqlException
      Response.Write(ex.ToString())
    End Try
  End Sub

The next section of code shows how we get to the data that was typed in the insert textbox and then updates the table in the database. As you can see, we use the FindControl method to locate the textbox containing insertable data. We use its text property to insert the data into the table. In this example the ShippperID column is an Identity column so we do not have to set a value for it in our INSERT statement. If you have more than one column to be inserted you would dimension multiple textbox objects to grab the data from the appropriate textboxes in the footer and expand your INSERT statement accordingly.
  Private Sub DataGrid1_ItemCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs) Handles DataGrid1.ItemCommand
    If e.CommandName = "Insert" Then
      Dim tb1 As TextBox = e.Item.FindControl("txtCompanyName")
      If tb1.Text.Trim() <> "" Then
        Dim strSQL As String
        Try
          sqlConn = New SqlConnection(ConfigurationSettings.AppSettings("ConnectionString"))
          strSQL = "INSERT INTO Shippers(CompanyName) values('" & tb1.Text.Trim() & "')"
          sqlConn.Open()
          sqlCmd = New SqlCommand(strSql, sqlConn)
          sqlCmd.ExecuteNonQuery()
          BindGrid()
        Catch ex As SqlException
          Response.Write(ex.ToString())
        End try
      End If
    End If
  End Sub

  Sub ChangePage(sender As Object, e As DataGridPageChangedEventArgs)
    DataGrid1.CurrentPageIndex = e.NewPageIndex
    BindGrid()
  End Sub

End Class

I hope the code presented has been clear enough and the minimal explanation of it sufficient.

You may download the code here.