8.7. Modifying and Updating Data in a Web Forms GridView Control

Problem

You need to edit data using a GridView 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 using a data adapter.

Follow these steps:

  1. The solution uses a table named GridView in the AdoDotNet35Cookbook database.

    Execute the following T-SQL statement to create the table:

    	USE AdoDotNet35Cookbook
    	GO
    	CREATE TABLE GridView(
    	    Id int NOT NULL PRIMARY KEY,
    	    IntField int NULL,
    	    StringField nvarchar(50) NULL )

    The schema of table GridView used in this solution is shown in Table 8-9.

    Table 8-9. GridView table schema

    Column name

    Data type

    Length

    Allow nulls?

    Id

    int

    4

    No

    IntField

    int

    4

    Yes

    StringField

    nvarchar

    50

    Yes

  2. Execute the following T-SQL batch to create the sample data required by the solution:

    	USE AdoDotNet35Cookbook
    	GO
    	INSERT INTO GridView VALUES (1, 10, 'Field1.1')
    	INSERT INTO GridView VALUES (2, 20, 'Field1.2')
    	INSERT INTO GridView VALUES (3, 30, 'Field1.3')
    	INSERT INTO GridView VALUES (4, 40, 'Field1.4')
  3. Create a C# ASP.NET web application named UpdateDataWebFormGridView.

  4. Add the following control to the Default.aspx design surface:

    • GridView named gridView

    The completed layout of the Web Form page Default.aspx is shown in Figure 8-13.

    Layout for Default.aspx in UpdateDataWebFormGridView solution

    Figure 8-13. Layout for Default.aspx in UpdateDataWebFormGridView solution

The code ...

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