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)
{
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)
{
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" )
{
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" )
{
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)
{
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)
{
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)
{
scriptString = "<script language="JavaScript"> alert('New Item Added!')";
}
else
{
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:
- 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.
- 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.