7.5. Editing and Updating Data in a Web Forms DataGrid

Problem

You need to edit complex data using a DataGrid control and update the database with the changes made.

Solution

Bind the results of a database query to a DataGrid control and update the database with changes made in the DataGrid by configuring the appropriate properties and events.

The schema of table TBL00705 used in this solution is shown in Table 7-7.

Table 7-7. TBL0705 schema

Column name

Data type

Length

Allow nulls?

Id

int

4

No

IntField

int

4

Yes

StringField

nvarchar

50

Yes

The Web Forms page sample code defines the DataGrid control with the four columns that it contains—Edit or Update/Cancel button, Delete button, Id field, IntField field, StringField field—and the two templates controlling the appearance of data depending on whether the column is being edited: EditItemTemplate or ItemTemplate. The static Eval( ) method of the DataBinder class is used to fill the field values in each template. The Container.DataItem specifies the container argument for the method which, when used in a data grid, resolves to DataGridItem.DataItem. The code for the Web Forms page is shown in Example 7-9.

Example 7-9. File: ADOCookbookCS0705.aspx

<asp:DataGrid id="dataGrid" style="Z-INDEX: 102; LEFT: 16px; POSITION: absolute; TOP: 56px" runat="server" Width="576px" AutoGenerateColumns="False" PageSize="5" AllowPaging="True" AllowSorting="True"> <AlternatingItemStyle BackColor="#FFFF99"> </AlternatingItemStyle> <HeaderStyle ...

Get ADO.NET Cookbook 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.