2.16. Editing Data in a GridView

Problem

You want to allow the user to edit the data within the table displayed by a GridView.

Solution

Add a GridView and an updateable data source, such as an asp:SqlDataSource, to the .aspx file, set the AutoGenerateEditButton attribute of the GridView control to true, add EditItemTemplate elements for each column that is to be editable, and initialize the properties of the data source in the code-behind.

In the .aspx file:

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

  • Add an asp:SqlDataSource.

  • Set the AutoGenerateEditButton attribute of the GridView to true.

  • Add EditItemTemplate elements for each editable column.

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

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

  • Initialize the UpdateCommand property of the SqlDataSource to the SQL statement used to update with parameters for the data the user can edit.

  • Add the parameters for the data the user can update to the UpdateParameters collection of the SqlDataSource.

  • Set the DataKeyNames collection of the SqlDataSource to the primary key(s) used to identify a unique row of data in the GridView.

Figure 2-17 shows the output of a typical example in normal mode and Figure 2-18 shows the output in edit mode. Examples 2-42, 2-43 through 2-44 show the .aspx file and the code-behind files for an application that produces ...

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.