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:
The solution uses a table named
DataGridViewin theAdoDotNet35Cookbookdatabase. 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 )
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')
Create a C# Windows Forms application,
UpdateDataWindowsFormDataGridView.Add the following controls to the
Form1design surface:DataGridViewnameddataGridViewButtonnamedsaveButtonwithTextproperty =Save
The completed layout of the Windows Form named
Form1is shown in Figure 8-29.
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 ...
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