|
Free
C# Tutorials
|
![]() |
home |
Stay
at Home and Learn
|
|||||
Update and Delete Records |
||||||
|
<< Part of an ongoing lesson - first part is here >> Sometimes, all you want to do is to update a record in the database. This is very similar to Adding a new record. Examine the following code:
The only thing you're not doing is adding a new Row. After creating a new Row called dRow2, we set it to the current Row: = ds1.Tables["Workers"].Rows[inc]; Whatever is in the text boxes then gets transferred to dRow2[1], dRow2[2] and dRow2[3]. These are the Columns in the Row. Then we update the database: da.Update( ds1, "Workers" ); Before trying it out, comment out the line that says con.Dispose(), if you added one. Otherwise you'll get a Connection String error. When you run your form, amend one of your records. Close down the form and open it back up again. You should find that your amendments are still there.
Delete a RecordTo delete a record from the Dataset, you use the Delete method: ds1.Tables["Workers"].Rows[inc].Delete(); This is enough to Delete the entire Row ( Rows[inc] ). But it is only deleted from the Dataset. Here's the code to delete the record from the database, as well:
Notice that we're deducting 1 from the MaxRows variable ( MaxRows-- ), as well as setting inc to 0. Try it out for yourself. Add a new record to your database. Then try to Delete it. You may get an error about concurrency violations. If you close down the programme and open it back up again, you should find that you'll be able to delete it without any errors. Concurrency violations can happen for many reasons, but in general
it's because the Dataset and Database are out of sync with one another.
The easiest solution is to set a Boolean value when a new record is
added. If you try to delete, check if this value is true. If it is,
then let your user known that they can't delete this new record.
Exercise
If you look at the bottom, you'll see a label that says "Record 2 of 4". Implement this in your own programme. If you set up a method, you can just call it when the form loads, and again from NavigateRecords.
In the next lesson. learn how to find records in a Database.
<-- Add a New Record | Find records in a Database --> <--Back to the C# .NET Contents Page View all our Home Study Computer Courses
|