Changing Database Records
So far, you’ve retrieved data from a database, but you haven’t manipulated its records in any way. Using ADO.NET, it is of course possible to add a record, change an existing record, or delete a record altogether.
In a typical implementation, you might work your way through the following steps:
Fill the tables for your
DataSet
using a stored procedure or SQL.Display the data in various
DataTable
objects within yourDataSet
by either binding to a control or looping through the rows in the tables.Change data in individual
DataTable
objects by adding, modifying, or deletingDataRow
objects.Invoke the
GetChanges( )
method to create a secondDataSet
that features only the changes to the data.Check for errors in the second newly created
DataSet
by examining theHasErrors
property. If there are errors, check theHasErrors
property of eachDataTable
in theDataSet
. If the table has errors, invoke theGetErrors( )
method of theDataTable
and get back an array ofDataRow
objects with errors. On each row, you can examine theRowError
property for specific information about the error, which you can then resolve.Merge the second
DataSet
with the first.Call the
Update( )
method on theDataAdapter
object and pass in the second (changed)DataSet
.Invoke the
AcceptChanges( )
method on theDataSet
, or invokeRejectChanges( )
to cancel the changes.
This process gives you very fine control over the update to your data as well as an opportunity to fix any data ...
Get Programming C#, Third 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.