Click here to Skip to main content
12,813,675 members (33,266 online)
Click here to Skip to main content
Add your own
alternative version


1 download
68 bookmarked
Posted 19 Dec 2005

ASP.NET GridView - Add a new record

, 19 Dec 2005
Rate this:
Please Sign up or sign in to vote.
ASP.NET GridView - how to add a new record.


This code drop is part of a Smash and Grab series for the seriously ADD (Attention Deficit Disorder) programmer. I'll bet there are a lot of other programmers out there who would like to make code available to others, but just don't want to spend the hours required to create a full-blown "CodeProject" article. This is an attempt to see if I can make some useful code available to other programmers, and do it in 10 minutes. I encourage others to contribute to "Smash and Grab".

The point of this series is to present usable pre-canned classes or techniques which solve a real world problem without going into too much detail about how it works. I mean, who really cares about how System.Collections.ArrayList works, you just use it.

Please fully comment the code so that the person who really cares (and has the time) will be able to understand the underlying algorithm.

Using the code

There has been a lot of whining on the net about what a train-wreck the ASP.NET 2.0 GridView is because it won't do inserts and if the table source is empty, the grid does not even render.

Here is a solution in less than 15 lines of code.

  • Create a GridView as usual (I am using the NorthWind Categories table as an example).
  • Create the data source.
  • Change:
    SelectCommand="SELECT [CategoryID], [CategoryName]," + 
                " convert(nvarchar(1000),[Description]) FROM [Categories]";


    SelectCommand="SELECT '' as [CategoryID], '' as [CategoryName]," + 
             " '' as [Description] UNION SELECT [CategoryID]," + 
             " [CategoryName], convert(nvarchar(1000),[Description])" + 
             " FROM [Categories]";

    This inserts a blank row as the first line of the grid.

    This is the line that you will be editing to add the new record.

  • Add:

    as an event to the grid (you can do it through the GUI).

  • Add the highlighted JavaScript code.

    It finds the first "Edit Delete" text and changes it to "Add".

  • Add the "GridView1_RowAdding" method.

OnRowUpdating is called by the GridView before it updates a row. The GridView thinks it is doing an update to CategoryID=0 (which will silently fail). Meanwhile, you are scooping the data and doing a secret insert.

<%@ Page Language="C#" AutoEventWireup="true" 
             CodeFile="AddUpdate.aspx.cs" Inherits="AddUpdate" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 

<html xmlns="" >
<head runat="server">
    <title>Untitled Page</title>
    function FixGrid(idGrid)
      // content looks like:
      //"<A href=\"javascript:__doPostBack('GridView1',
      //    'Edit$0')\">Edit</A> 
      // <A href=\"javascript:__doPostBack('GridView1',
      //    'Delete$0')\">Delete</A>"
      // replace Edit with Add, remove Delete
      var Parts = 
      var tmp = Parts.join(">Add<"); 
      Parts = tmp.split(">Delete<");
      idGrid.firstChild.childNodes[1].childNodes[0].innerHTML = 
    <form id="form1" runat="server">
        <asp:GridView ID="GridView1" runat="server" 
                 AutoGenerateColumns="False" DataKeyNames="CategoryID"
                <asp:CommandField ShowDeleteButton="True" 
                    ShowEditButton="True" />
                <asp:BoundField DataField="CategoryID" 
                    HeaderText="CategoryID" InsertVisible="False"
                    ReadOnly="True" SortExpression="CategoryID" />
                <asp:BoundField DataField="CategoryName" 
                       SortExpression="CategoryName" />
                <asp:BoundField DataField="Description" 
                       SortExpression="Description" />
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
              ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
            DeleteCommand="DELETE FROM [Categories] 
                           WHERE [CategoryID] = @CategoryID"
            InsertCommand="INSERT INTO [Categories] 
                           ([CategoryName], [Description]) 
                           VALUES (@CategoryName, @Description)"
            SelectCommand="SELECT '' as [CategoryID], 
                '' as [CategoryName], '' as [Description]
                UNION SELECT [CategoryID], [CategoryName], 
                FROM [Categories]" 
            UpdateCommand="UPDATE [Categories] SET 
                           [CategoryName] = @CategoryName, 
                           [Description] = @Description 
                           WHERE [CategoryID] = @CategoryID">
                <asp:Parameter Name="CategoryID" Type="Int32" />
                <asp:Parameter Name="CategoryName" Type="String" />
                <asp:Parameter Name="Description" Type="String" />
                <asp:Parameter Name="CategoryID" Type="Int32" />
                <asp:Parameter Name="CategoryName" Type="String" />
                <asp:Parameter Name="Description" Type="String" />
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class AddUpdate : System.Web.UI.Page
    protected void Page_Load(object sender, EventArgs e)


    protected void GridView1_RowAdding(object sender, 
                        GridViewUpdateEventArgs e)
        if (e.RowIndex > 0)
            return; // RowIndex=0 is the row we want to insert
        System.Collections.Hashtable h = 
                    new System.Collections.Hashtable();

        foreach (System.Collections.DictionaryEntry x in e.NewValues)
            h[x.Key] = x.Value;
        // you now have the data to insert in a hashtable
        // get it into the database using your
        // usual Data Access Layer methods



This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


About the Author

Gary Dryden
Software Developer (Senior)
Canada Canada
No Biography provided

You may also be interested in...

Comments and Discussions

GeneralQuick and Easy fix for insert record Pin
drewster116-Jun-11 23:44
memberdrewster116-Jun-11 23:44 
GeneralWorks well for me, but problems arise with paging. Pin
stapes14-Apr-11 0:56
memberstapes14-Apr-11 0:56 
GeneralDoes not work in Firefox Pin
stapes5-Apr-11 2:06
memberstapes5-Apr-11 2:06 
GeneralRe: Does not work in Firefox Pin
stapes14-Apr-11 1:50
memberstapes14-Apr-11 1:50 
Generalerror ! Pin
sharathu730-Dec-10 22:59
membersharathu730-Dec-10 22:59 
Generaldisplay blank grid in add/edit/update mode on UI Pin
Mr. MAHESHKUMAR6-Jan-10 0:28
memberMr. MAHESHKUMAR6-Jan-10 0:28 
GeneralEliminating GridView1_RowAdding Pin
Roy Oliver6-Aug-09 8:25
memberRoy Oliver6-Aug-09 8:25 
GeneralRe: Eliminating GridView1_RowAdding Pin
Roy Oliver6-Aug-09 10:20
memberRoy Oliver6-Aug-09 10:20 
GeneralGridview Pin
ksarchana3-Jan-09 1:47
memberksarchana3-Jan-09 1:47 
GeneralCorrected javascript for IE, FF, and Safari Pin
karen_webexc30-Jul-08 5:12
memberkaren_webexc30-Jul-08 5:12 
GeneralPls provide the code for inserting data in hashtable using DAL Pin
Member 315998723-Jul-08 8:21
memberMember 315998723-Jul-08 8:21 
QuestionHow to place data from SQLSERVER into gridview and then edit and delete data Pin
waseemtalib27-May-08 19:55
memberwaseemtalib27-May-08 19:55 
GeneralAlternative insert/update code Pin
Paul /)/+)16-Oct-07 1:52
memberPaul /)/+)16-Oct-07 1:52 
QuestionWorks great except for Paging & Sorting... Pin
imxuf17-Jul-07 13:46
memberimxuf17-Jul-07 13:46 
GeneralHere is how you can make it work on multiple GridViews Pin
HamidTheProgrammer28-Mar-07 11:42
memberHamidTheProgrammer28-Mar-07 11:42 
GeneralDoes't Work Pin
Member #376055221-Mar-07 3:40
memberMember #376055221-Mar-07 3:40 
GeneralAnother method to change to ADD link - Use RowDataBound [modified] Pin
dbernett15-Nov-06 7:15
memberdbernett15-Nov-06 7:15 
GeneralRe: Another method to change to ADD link - Use RowDataBound Pin
ccshine5-Dec-06 13:42
memberccshine5-Dec-06 13:42 
GeneralBut, if we use sorting for the same grid Pin
kvPriya5-Oct-06 19:41
memberkvPriya5-Oct-06 19:41 
GeneralI fix the javascript for the linkbutton names. Check it out! Pin
kampfer!24-Sep-06 10:52
memberkampfer!24-Sep-06 10:52 
Questiondoesnt work with strongly typed datasets Pin
xgnitesh13-Sep-06 21:52
memberxgnitesh13-Sep-06 21:52 
QuestionRe: doesnt work with strongly typed datasets [modified] Pin
rbm_the_spitfire2-Oct-06 23:09
memberrbm_the_spitfire2-Oct-06 23:09 
GeneralGood, but the Edit,Delete are not being replaced by Add Pin
kvPriya8-Sep-06 19:38
memberkvPriya8-Sep-06 19:38 
GeneralRe: Good, but the Edit,Delete are not being replaced by Add Pin
zwitterion14-Sep-06 8:55
memberzwitterion14-Sep-06 8:55 
GeneralRe: Good, but the Edit,Delete are not being replaced by Add Pin
Vincent D'Souza25-Oct-06 6:55
memberVincent D'Souza25-Oct-06 6:55 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.170308.1 | Last Updated 19 Dec 2005
Article Copyright 2005 by Gary Dryden
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid