Click here to Skip to main content
Licence 
First Posted 19 Dec 2005
Views 332,357
Bookmarked 68 times

ASP.NET GridView - Add a new record

By Gary Dryden | 19 Dec 2005
ASP.NET GridView - how to add a new record.
 
Part of The SQL Zone sponsored by
See Also
4 votes, 21.1%
1
2 votes, 10.5%
2
1 vote, 5.3%
3
3 votes, 15.8%
4
9 votes, 47.4%
5
4.37/5 - 19 votes
4 removed
μ 3.94, σa 2.94 [?]

Introduction

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]";

    to:

    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:
    OnRowUpdating="GridView1_RowAdding";

    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" 
      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
    <script>
    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 = 
       idGrid.firstChild.childNodes[1].childNodes[0].innerHTML.split(">Edit<");
      var tmp = Parts.join(">Add<"); 
      Parts = tmp.split(">Delete<");
      idGrid.firstChild.childNodes[1].childNodes[0].innerHTML = 
                                        Parts.join("><");
    }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" 
                 AutoGenerateColumns="False" DataKeyNames="CategoryID"
            DataSourceID="SqlDataSource1" 
                    OnRowUpdating="GridView1_RowAdding">
            <Columns>
                <asp:CommandField ShowDeleteButton="True" 
                    ShowEditButton="True" />
                <asp:BoundField DataField="CategoryID" 
                    HeaderText="CategoryID" InsertVisible="False"
                    ReadOnly="True" SortExpression="CategoryID" />
                <asp:BoundField DataField="CategoryName" 
                       HeaderText="CategoryName" 
                       SortExpression="CategoryName" />
                <asp:BoundField DataField="Description" 
                       HeaderText="Description" 
                       SortExpression="Description" />
            </Columns>
        </asp:GridView>
        <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], 
                convert(nvarchar(1000),[Description])
                FROM [Categories]" 
            UpdateCommand="UPDATE [Categories] SET 
                           [CategoryName] = @CategoryName, 
                           [Description] = @Description 
                           WHERE [CategoryID] = @CategoryID">
            <DeleteParameters>
                <asp:Parameter Name="CategoryID" Type="Int32" />
            </DeleteParameters>
            <UpdateParameters>
                <asp:Parameter Name="CategoryName" Type="String" />
                <asp:Parameter Name="Description" Type="String" />
                <asp:Parameter Name="CategoryID" Type="Int32" />
            </UpdateParameters>
            <InsertParameters>
                <asp:Parameter Name="CategoryName" Type="String" />
                <asp:Parameter Name="Description" Type="String" />
            </InsertParameters>
        </asp:SqlDataSource>
    
    </div>
    </form>
        <script>
            FixGrid(document.all.GridView1);
        </script>
</body>
</html>
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

    }
}

License

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

Member


Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralQuick and Easy fix for insert record Pinmemberdrewster1123:44 6 Jun '11  
GeneralWorks well for me, but problems arise with paging. Pinmemberstapes0:56 14 Apr '11  
GeneralDoes not work in Firefox Pinmemberstapes2:06 5 Apr '11  
GeneralRe: Does not work in Firefox Pinmemberstapes1:50 14 Apr '11  
Generalerror ! Pinmembersharathu722:59 30 Dec '10  
Generaldisplay blank grid in add/edit/update mode on UI PinmemberMr. MAHESHKUMAR0:28 6 Jan '10  
I want to display blank GridView with one row and 5 columns on the UI for that the user can insert value into Database with that grid.
GeneralEliminating GridView1_RowAdding PinmemberRoy Oliver8:25 6 Aug '09  
GeneralRe: Eliminating GridView1_RowAdding PinmemberRoy Oliver10:20 6 Aug '09  
GeneralGridview Pinmemberksarchana1:47 3 Jan '09  
GeneralCorrected javascript for IE, FF, and Safari Pinmemberkaren_webexc5:12 30 Jul '08  
GeneralPls provide the code for inserting data in hashtable using DAL PinmemberMember 31599878:21 23 Jul '08  
QuestionHow to place data from SQLSERVER into gridview and then edit and delete data Pinmemberwaseemtalib19:55 27 May '08  
GeneralAlternative insert/update code PinmemberPaul /)/+)1:52 16 Oct '07  
QuestionWorks great except for Paging & Sorting... Pinmemberimxuf13:46 17 Jul '07  
GeneralHere is how you can make it work on multiple GridViews PinmemberHamidTheProgrammer11:42 28 Mar '07  
GeneralDoes't Work PinmemberMember #37605523:40 21 Mar '07  
GeneralAnother method to change to ADD link - Use RowDataBound [modified] Pinmemberdbernett7:15 15 Nov '06  
GeneralRe: Another method to change to ADD link - Use RowDataBound Pinmemberccshine13:42 5 Dec '06  
GeneralBut, if we use sorting for the same grid PinmemberkvPriya19:41 5 Oct '06  
GeneralI fix the javascript for the linkbutton names. Check it out! Pinmemberkampfer!10:52 24 Sep '06  
Questiondoesnt work with strongly typed datasets Pinmemberxgnitesh21:52 13 Sep '06  
QuestionRe: doesnt work with strongly typed datasets [modified] Pinmemberrbm_the_spitfire23:09 2 Oct '06  
GeneralGood, but the Edit,Delete are not being replaced by Add PinmemberkvPriya19:38 8 Sep '06  
GeneralRe: Good, but the Edit,Delete are not being replaced by Add Pinmemberzwitterion8:55 14 Sep '06  
GeneralRe: Good, but the Edit,Delete are not being replaced by Add PinmemberVincent D'Souza6:55 25 Oct '06  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    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 | Mobile
Web01 | 2.5.120210.1 | Last Updated 19 Dec 2005
Article Copyright 2005 by Gary Dryden
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid