8.15. Modifying and Updating Data in a Windows Forms DataGridView Control

Problem

You need to update a database with changes that you have made to data in a DataGridView control.

Solution

Use a DataAdapter to update the database with the changes in the data source for the DataGridView control.

Follow these steps:

  1. The solution uses a table named DataGridView in the AdoDotNet35Cookbook database. Execute the following T-SQL statement to create the table:

    	USE AdoDotNet35Cookbook
    	GO
    	CREATE TABLE DataGridView(
    	    Id int NOT NULL PRIMARY KEY,
    	    IntField int NULL,
    	    StringField nvarchar(50) NULL )
  2. Execute the following T-SQL batch to create the sample data required by the solution:

    	USE AdoDotNet35Cookbook
    	GO
    	INSERT INTO DataGridView VALUES (1, 10, 'Field1.1')
    	INSERT INTO DataGridView VALUES (2, 20, 'Field1.2')
    	INSERT INTO DataGridView VALUES (3, 30, 'Field1.3')
    	INSERT INTO DataGridView VALUES (4, 40, 'Field1.4')
  3. Create a C# Windows Forms application, UpdateDataWindowsFormDataGridView.

  4. Add the following controls to the Form1 design surface:

    • DataGridView named dataGridView

    • Button named saveButton with Text property = Save

    The completed layout of the Windows Form named Form1 is shown in Figure 8-29.

    Layout for Form1 in UpdateDataWindowsFormDataGridView solution

    Figure 8-29. Layout for Form1 in UpdateDataWindowsFormDataGridView solution

The C# code in Form1.cs in the project UpdateDataWindowsFormDataGridView is shown in Example 8-27. The code creates a DataTable that contains ...

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.