Adding a new, blank record to the data source of the grid (in the dataset or database). If necessary, you will need to assign an ID for the record and put placeholder values into it for any columns that cannot be null. Rebinding the DataGrid control to the source. Putting the grid into edit mode for the new record. You need to be able to determine where in the grid the new record appears. Updating the record normally when the user clicks Update, thereby writing the new record to the source with user-provided values. The following example shows the process for adding the new record, binding the grid, and putting it into edit mode. In this example, the data source is a dataset (DsBooks1 or dsBooks1) containing a table called "Books."
' Visual Basic Private Sub btnAddRow_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnAddRow.Click Dim dr As DataRow = Me.DsBooks1.Books.NewRow dr("title") = "(New)" dr("instock") = True Me.DsBooks1.Books.Rows.InsertAt(dr, 0) Session("DsBooks") = DsBooks1 DataGrid1.EditItemIndex = 0 DataGrid1.DataBind() End Sub
// C# private void btnAddRow_Click(object sender, System.EventArgs e) { DataRow dr = this.dsBooks1.Books.NewRow(); dr["title"] = "(New)"; dr["instock"] = true; this.dsBooks1.Books.Rows.InsertAt(dr, 0); Session["DsBooks"] = dsBooks1; DataGrid1.EditItemIndex = 0; DataGrid1.DataBind(); } Some things to notice:
This code runs when a user clicks an Add button somewhere in the page. The new row is created using the NewRow method. It is then inserted into the dataset table using the InsertAt method, which allows you to place it at a specific, predefined location — in this case, as the first record in the table (that is, the first record in the Rows collection). Alternatively, you could add it to the end of the table, using the row count as the value. The important thing is that you know exactly where the row is in the table. Because you know that the record is in the first position of the table, you can set the grid's EditItemIndex value to zero to put the new row into edit mode. (If you created the row elsewhere in the table, you would set EditItemIndex to that location instead.) Because you have a new record in the dataset (but not yet in the database), you have to keep a copy of the dataset between round trips — you do not want to refill it from the database and lose the new record. Here, the code stores it in Session state. You need to reload the dataset from Session state when the page loads. The following example shows what your Page_Load handler might look like: