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
GridViewcontrol where the data is to be displayed.Add an
asp:SqlDataSource.Set the
AutoGenerateEditButtonattribute of theGridViewto true.Add
EditItemTemplateelements 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
SelectCommandproperty of theSqlDataSourceto the SQL statement used to get the data to display from the database.Initialize the
UpdateCommandproperty of theSqlDataSourceto 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
UpdateParameterscollection of theSqlDataSource.Set the
DataKeyNamescollection of theSqlDataSourceto the primary key(s) used to identify a unique row of data in theGridView.
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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access