Click here to Skip to main content
Click here to Skip to main content

Insert a New Row using DataGrid Hidden Columns

, 23 Jun 2005
Rate this:
Please Sign up or sign in to vote.
Use the DataGrid to easily enter new data values with a hidden row.

Sample Image - DataGridInsert.jpg

Introduction

This is a very simple example of how to use the DataGrid control in ASP.NET pages to enter new data by creating a hidden empty row at the first row position in the grid. This has a very clean look, and avoids designing a new page just to enter the data in individual fields.

Getting Started

Start by creating a web page in Visual Studio with a DataGrid and a button for inserting the new row. Right-click on the grid and use AutoFormat to design the look, or go right into Property Builder and format the properties as you like. In the Property Builder, select Columns and expand the Button Column under Available Columns. Now add an Edit/Update/Cancel button by highlighting that selection and pressing the '>' button. The Edit, Update, and Cancel text at the bottom should be noted. If you change this text, you will need to know that for the code. Save the grid properties and close the Property Builder.

Creating Events

Once the Edit link button is added to the grid, the events associated with the link must be assigned. Right-click on the grid and open the Properties window. Click on the Events button at the top that looks like a lightning bolt. You need to add events for the Edit, Update, and Cancel commands, as well as the ItemCreated event. Enter a method name for each of these events by clicking in the empty box to the right of the event and typing in a name. I used the names, OnGridItemEdit, OnGridItemUpdate, OnGridItemCancel, and OnGridItemCreated. When you enter each name, you will be taken to the code behind, and you will have to come back to the page display each time.

After the edit events are complete, double-click on the Insert button you added, and a new method for the button click event will be automatically added, ready for coding.

Writing the Code

The code can now be entered to handle the tasks of creating a hidden "dummy" row for inserts, and handling all events when rows are created and edited.

In order to simulate some type of data source, I just used the CreateDataSource method from the help topics. This is just a simple DataTable creation that populates some rows with random data. I modified the code slightly to add an empty row at position 0:

ICollection CreateDataSource() 
{
  DataTable dt = new DataTable();
  DataRow dr;

  dt.Columns.Add(new DataColumn("IntegerValue", typeof(Int32)));
  dt.Columns.Add(new DataColumn("StringValue", typeof(string)));
  dt.Columns.Add(new DataColumn("CurrencyValue", typeof(double)));

  for (int i = 0; i < 9; i++) 
  {
    dr = dt.NewRow();
    if (i == 0)
    {
      /* first row will be hidden insert row */
      dr[0] = -1;
      dr[1] = "";
      dr[2] = -1;
    }
    else
    {
      dr[0] = i;
      dr[1] = "Item " + i.ToString();
      dr[2] = 1.23 * (i + 1);
    }

    dt.Rows.Add(dr);
  }

  DataView dv = new DataView(dt);
  return dv;
}

Next, I bind the data source to the grid in the initial Page_Load:

private void Page_Load(object sender, System.EventArgs e)
{
    if (!IsPostBack)
    {
      /* Load this data only once. */
      DataGrid1.DataSource= CreateDataSource();
      DataGrid1.DataBind();
    }

}

Now, for the events.

The first event handler to look at is the OnGridItemCreated method, which is called when each row in the DataGrid is being created. This is where we want to hide the first row in the data source which is the dummy row. This is done by setting the Visible property to false for all the columns in the row at position 0 when the item is not being edited. If this row is being edited, we would know that, because the first control's text would change to the Update text:

Notice also that I don't want to allow editing on the first data column for existing items. This is typically a primary key in many real-world applications, so this can come in handy.

private void OnGridItemCreated(object sender, 
             System.Web.UI.WebControls.DataGridItemEventArgs e)
{
  if ( e.Item.ItemIndex == 0 ) 
  {
    System.Web.UI.WebControls.LinkButton lb = 
      ( System.Web.UI.WebControls.LinkButton )e.Item.Cells[0].Controls[0];
    if ( lb.Text == "Edit" ) 
    {
      /* If this is row 0 and not inserting, hide the row */
      lb.Text = "";
      e.Item.Cells[0].Visible = false;
      e.Item.Cells[1].Visible = false;
      e.Item.Cells[2].Visible = false;
      e.Item.Cells[3].Visible = false;
    }
    else if ( lb.Text == "Update" ) 
    {
      /* If inserting, make row visible */
      lb.Text = "Insert";
      e.Item.Cells[0].Visible = true;
      e.Item.Cells[1].Visible = true;
      e.Item.Cells[2].Visible = true;
      e.Item.Cells[3].Visible = true;
    } 
  }
  else if (e.Item.ItemIndex > 0)
  {
    /* Make first data column read-only for existing items */
    System.Web.UI.WebControls.LinkButton lb = 
      ( System.Web.UI.WebControls.LinkButton )e.Item.Cells[0].Controls[0];
    if (lb.Text == "Update")
    {
      if (e.Item.Cells[1].Controls.Count > 0)
        ((TextBox)e.Item.Cells[1].Controls[0]).Enabled = false;
    }
  }
}

The next event handler to look at is the method that is called when the Insert button is pressed. This event will signal that the hidden row is to be edited, and must be made visible. This occurs by setting the DataGrid's EditItemIndex to 0, which means row 0 is now being edited. The DataGrid will change the "Edit" text to "Update Cancel" for the link button in the row at position 0. This in turn signals the ItemCreated event to now display the row. Note that for this example, the data source is rebound and the Insert button disabled.

private void btnInsert_Click(object sender, System.EventArgs e)
{
  /* The hidden row at position 0 will be used to enter data */
  DataGrid1.EditItemIndex = 0;
  DataGrid1.DataSource= CreateDataSource();
  DataGrid1.DataBind();
  btnInsert.Enabled = false;
}

The Edit and Cancel events are very similar to the Insert event, and simply set or remove the row to be edited:

private void OnGridItemCancel(object source, 
             System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
  DataGrid1.EditItemIndex = -1;
  DataGrid1.DataSource= CreateDataSource();
  DataGrid1.DataBind();
  btnInsert.Enabled = true;
}

private void OnGridItemEdit(object source, 
             System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
  DataGrid1.EditItemIndex = e.Item.ItemIndex;
  DataGrid1.DataSource= CreateDataSource();
  DataGrid1.DataBind();
  btnInsert.Enabled = false;
}

Finally, the Update event is coded to accept either the new row, or the changed row. I did not go into the details of getting the data out of the grid rows and actually updating the grid. As I really do not have a true data source, there was nothing to update, and I didn't want to complicate the original intention of this example which is to show how to insert with a hidden row. Therefore, the Update event is simply a template to be filled in, and just gives a nice message box to inform you that something happened. Note that the EditItemIndex is cleared and the button is enabled once again:

private void OnGridItemUpdate(object source, 
             System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
  String scriptString = "";
  if (e.Item.ItemIndex == 0)
  {
    /* code here to add new item */
    scriptString = "<script language="JavaScript"> alert('New Item Added!')";
  }
  else
  {
    /* code here to update existing item */
    scriptString = "<script language="JavaScript"> alert('Item Updated!')";
  }
  scriptString += "<";
  scriptString += "/";
  scriptString += "script>";
  if(!this.IsClientScriptBlockRegistered("clientScript"))
    this.RegisterClientScriptBlock("clientScript", scriptString);
  DataGrid1.EditItemIndex = -1;
  DataGrid1.DataSource= CreateDataSource();
  DataGrid1.DataBind();
  btnInsert.Enabled = true;
}

Some Notes

This example shows a very simple way to insert new data into a DataGrid with a nice clean interface and easy coding. Here are a few things you should pay particular attention to when using this type of functionality:

  1. You will need to know how many and the type of columns that are represented by your data source(s). This can be tricky when automatic column creation is being used. You may find that certain types will require a value in the dummy row because it is a non-null field or something.
  2. If you want sortable columns, you must make sure that the values in the dummy row are always going to be positioned in row 0. This can be done by adding the dummy row after the sort.

I hope you find this example as useful as I did.

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

Share

About the Author

Bob Carboni
Web Developer
United States United States
Software architect and developer with over 20 years of experience, specializing in GUI designs and intranet systems in MFC/C++ and ASP.Net using C#.

Comments and Discussions

 
GeneralMy vote of 1 Pinmemberserhu10-Dec-09 5:03 
Generalinsert a new record at the 1st row position Pinmemberasahmedshareef20-Jul-08 1:26 
Generalright click on grid Pinmembersobhaniir25-Feb-08 2:06 
AnswerRe: right click on grid Pinmemberdoran_doran4-Mar-09 20:37 
Generalinsert a new row in datagrid by using dataset not on datbase Pinmemberdhee_king31-Oct-07 2:06 
QuestionHow to Delete a row ? PinmemberAther Ali Shaikh29-Dec-06 1:31 
GeneralOh man ur code is not running plese test that PinmemberHarryBeck231-Oct-06 9:33 
GeneralPROBLEM Pinmemberthehatch13-Jan-06 10:25 
GeneralRe: PROBLEM PinmemberBob Carboni13-Jan-06 11:31 
GeneralRe: PROBLEM Pinmemberthehatch13-Jan-06 14:04 
GeneralRe: PROBLEM Pinmemberthehatch14-Jan-06 6:16 
GeneralAnother way PinmemberAbishek Bellamkonda29-Jun-05 14:47 
GeneralRe: Another way PinsussAgreed29-Jun-05 14:55 
GeneralRe: Another way PinmemberBob Carboni30-Jun-05 5:54 
GeneralRe: Another way PinmemberAbishek Bellamkonda30-Jun-05 14:45 

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.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.141216.1 | Last Updated 23 Jun 2005
Article Copyright 2005 by Bob Carboni
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid