2.17. Inserting a Row Within a GridView

Problem

You want to provide the ability for a user to insert a new row of data within a GridView.

Solution

Add a GridView and an updateable data source, such as an asp:SqlDataSource, to the .aspx file, set the ShowFooter attribute of the GridView control to true, add Footer-Template elements for each column that is to be inserted, add an Insert button in the footer, and initialize the properties of the data source in the code-behind. When the user clicks the Insert button, set the parameter values from the entered data and use the data source to insert the data in the GridView's RowCommand event handler in the code-behind.

In the .aspx file:

  1. Add a GridView control where the data is to be displayed.

  2. Add an asp:SqlDataSource.

  3. Set the ShowFooter attribute of the GridView to true.

  4. Add FooterTemplate elements for each column that is to be inserted.

In the Page_Init event handler of the code-behind class for the page, use the .NET language of your choice to:

  1. Initialize the SelectCommand property of the SqlDataSource to the SQL statement used to get the data to display from the database.

  2. Initialize the InsertCommand property of the SqlDataSource to the SQL statement (with parameters) used to insert in the database the data the user enters.

  3. Add the parameters for the data the user can update to the InsertParameters collection of the SqlDataSource.

  4. In the RowCommand event handler, set the values of the InsertParameters of the SqlDataSource from the controls containing ...

Get ASP.NET 2.0 Cookbook, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.