O'Reilly logo

ADO.NET Cookbook by Bill Hamilton

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required