4.8. Updating a Primary Key Value
Problem
You changed a primary key value in a
DataTable and updated the change back to the
underlying data source, but the value in the data source remained
unchanged. You need to update a primary key value in the data source
underlying the DataTable.
Solution
Use the
SourceVersion
property of SqlParameter to update the primary key
value in the data source.
The schema of table TBL0408 used in this solution is shown in Table 4-3.
Table 4-3. TBL0408 schema
|
Column name |
Data type |
Length |
Allow nulls? |
|---|---|---|---|
|
Id |
|
4 |
No |
|
Field1 |
|
50 |
Yes |
|
Field2 |
|
50 |
Yes |
The sample code contains two event handlers:
Form.LoadSets up the sample by creating a single
DataTablecontaining an integer primary key calledIdand two string fields calledField1andField2. ADataAdapteris created and the select, delete, insert, and update commands are defined for it. Finally, the table is filled using theDataAdapterand the default view of the table is bound to the data grid on the form.- Update
Button.Click Calls the
Update( )method of theDataAdapterdefined in theForm.Loadevent to reconcile the changes made, including those made to the primary key, with the SQL Server database.
The C# code is shown in Example 4-11.
Example 4-11. File: UpdatePrimaryKeyForm.cs
// Namespaces, variables, and constants using System; using System.Configuration; using System.Data; using System.Data.SqlClient; private const String TABLENAME = "TBL0408"; private DataTable dt; private SqlDataAdapter ...
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