Update a Record
Sometimes, all you want to do is to update a record in the database, change a name, for example, or amend an address.Add a new button to your form. Call it btnUdate. Double click the button to get at the code. Add the following lines:
DataRow row = ds.Tables[0].Rows[inc];
row[1] = txtFirstName.Text;
row[2] = txtSurname.Text;
row[3] = txtJobTitle.Text;
row[4] = txtDepartment.Text;
This is very similar to the code for adding a new record. Again we start by
creating a DataRow object. This time, we place a specific row in the new object.
That row is one from the DataSet:row[2] = txtSurname.Text;
row[3] = txtJobTitle.Text;
row[4] = txtDepartment.Text;
ds.Tables[0].Rows[ inc ];
However, this is the old row. The new details are in the textboxes, the ones
you may have amended. To place the new details into the new row object, we simply
transfer the textbox date to a position in the row object:
row[1] = txtFirstName.Text;
row[2] = txtSurname.Text;
row[3] = txtJobTitle.Text;
row[4] = txtDepartment.Text;
All we need to do now is to make a call to the UpdateDatabase method
from our class. Again, we can do this in a try … catch block:row[2] = txtSurname.Text;
row[3] = txtJobTitle.Text;
row[4] = txtDepartment.Text;
try
{
{
objConnect.UpdateDatabase(ds);
MessageBox.Show("Record Updated");
}
catch (Exception err)
{
catch (Exception err)
{
MessageBox.Show(err.Message);
}
The only line we really need is this one:
objConnect.UpdateDatabase(ds);
This is the same as before: we're just passing our UpdateDatabase method the
name of the DataSet, which is called ds.The whole of the btnUpdate code is this:
Delete a Record
To delete a record from the Dataset, you use the Delete method on the DataSet:
ds.Tables[0].Rows[inc].Delete( );
This is enough to Delete the entire Row ( Rows[inc] ). But it is only
deleted from the Dataset. To delete if from the underlying database as well,
we can call our UpdateDatabase method again.
objConnect.UpdateDatabase(ds);
Because a row has been deleted, we need to change the value of our MaxRows
variable. We also need to deduct 1 from the inc variable, and make a
call NavigateRecords:
MaxRows = ds.Tables[0].Rows.Count;
inc--;
inc--;
NavigateRecords();
Add another button to your form. Call it btnDelete. Here's the whole
of the code to add to your new button:Exercise P
Examine this version of our form:
OK, that's enough of databases! It's a huge subject, obviously,
and many books have been written on the subject. We've only touched the surface
in these lessons, and encourage you to delve deeper. Especially if you want
a job as a programmer!
In the next section, we'll take a look at multiple forms.
0 comments:
Post a Comment