A GridView with an "Add New Row" button that makes a new row and goes into edit modeThis article describes an extension to the GridView component of ASP.NET 2 I find the normal behavior of a GridView is not enough. Sometime I have a GridView that shows a summary of the full contents of a database table, and I want an easy way to add a new row. When the new row is added, I'd like the new row to go straight into edit mode, enabling the user to enter data right into the new row, inside the DataGrid. Here is a diagram to illustrate this:
Here is how to set this up:
How to add a blank record to a GridViewTo add a blank row, I add an new blank record to the database table that the GirdView works on. There are various ways to add a blank record, such as by using a stored procedure, but I use a simple SQL "insert" statement as follows: string connectionString = @"Data Source=MYCOMPUTER\SQLEXPRESS;Initial Catalog=mydatabase;Integrated Security=True";
SqlConnection con = new SqlConnection(connectionString);
con.Open();
string sql = "insert into mytable values('','','','')";
SqlCommand command = new SqlCommand(sql, con);
command.ExecuteNonQuery();
con.Close();
After doing this you must synchronise the GridView's idea of the database with the actual database itself. To do this, use this code: gridview1.DataBind() Putting the GridView row into edit-modeThis piece of code goes through each row of the GridView in turn, and looks to see if the row is blank. It assumes that a blank row is the new row we just added, and it puts this row into edit mode by setting the EditIndex property of the GridView to the row number. Incidentally, you can force all rows out of edit mode by setting the EditIndex property to -1. int totalrows = GridView1.Rows.Count;
for (int r = 0; r < totalrows; r++)
{
if (GridVIew1.DataKeys[r].Values[1].ToString() == "")
{
GridVIew1.EditIndex = r;
break;
}
}
So, that is it, except for one problem. If the user clicks to add a new row, then changes their mind and clicks Cancel on the new row, we must delete the blank row from the database. You can do this by intercepting the ROwCommand event of the GridView and looking for a Cancel command. |