400
LESSON 35 Programming Databases, Part 1
MessageBoxIcon.Question);
if (result == DialogResult.Cancel)
{
// Cancel the close.
e.Cancel = true;
}
else if (result == DialogResult.Yes)
{
// Save the changes.
peopleNamesTableAdapter.Update(peopleDataSet);
// Make sure the save worked.
// If we still have unsaved changes, cancel.
e.Cancel = (this.peopleDataSet.HasChanges());
}
// Else the user doesn’t want to save
// the changes so just keep going.
}
}
If the dataset has unsaved changes, the code asks the user whether it should save the changes. If the
user clicks Cancel, the code sets
e.Cancel to true so the program doesn’t close the form.
If the user clicks Yes, the code call’s the table adapter’s
Update method to save the datasets changes
back to the database.
If the user clicks No, the code just continues and lets the form close without saving the changes.
DISPLAYING RECORDS ONE ROW AT A TIME
Instead of displaying a table’s records in a grid, you can display
the data one record at a time as shown in Figure 35-7.
With this kind of interface, you can click the navigation but-
tons on the
BindingNavigator to move through the records.
You can use the display controls (
TextBoxes in Figure 35-7) to
change a record’s values.
To build this interface, first create a data source as before. Then,
instead of dragging a table from the Data Sources window onto
the form, drag individual fields onto the form. For each field,
Visual Studio adds a label and an appropriate display control
(such as a
TextBox) to the form.
This version of the interface does most of the things the grid-based version does but in different
ways. One feature that is missing is the ability to easily add and delete records. In the previous ver-
sion, the grid lets you add and delete records. In the record-based version, you need to enable the
BindingNavigators Add New and Delete buttons. (You can also enable them in the grid-based
version if you like, but because the grid can handle those functions by itself, it’s not mandatory.)
FIGURE 357
596906c35.indd 400 4/7/10 12:34:51 PM
Try It
401
Fortunately this is fairly easy. Simply add code to the form’s Load event handler to enable the but-
tons. The following code shows how the PeopleFields example program (available in this lesson’s
code download) enables its buttons. The first comment and line of code that calls
Fill were auto-
matically generated when I dragged the first field from the Data Sources window onto the form. (I
reformatted the comment slightly because it was too long to fit in the following listing.)
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the
// ‘peopleDataSet.PeopleNames’ table. You can move,
// or remove it, as needed.
this.peopleNamesTableAdapter.Fill(this.peopleDataSet.PeopleNames);
// Enable the Add New and Delete buttons.
this.bindingNavigatorDeleteItem.Enabled = true;
this.bindingNavigatorAddNewItem.Enabled = true;
}
As in the PeopleGrid example program (discussed earlier in this lesson and also available in the lesson’s
code download), the code created by Visual Studio doesn’t check for unsaved changes before the form
closes. You can solve this problem by adding a
FormClosing event to check for unsaved changes.
This version of the program works a little differently than the previous grid-style version, however.
The
DataGridView control used by the previous program automatically marks the data as modified
when the user starts changing a value. In contrast, the new program marks the data as modified
only when the user changes a value and then moves to a new record. That means if the user changes
a value and then tries to close the form without moving to a new record, the program doesnt know
there is an unsaved change and closes.
To prevent that, you can add the following two lines to the beginning of the
FormClosing event
handler:
this.Validate();
this.peopleNamesBindingSource.EndEdit();
These lines make the program officially finish editing any fields that the user is modifying so the
dataset knows that it has a pending change.
After that, the
FormClosing event handler works exactly as before.
TRY IT
In this Try It, you have a chance to practice the techniques described in this lesson. You create
an application that displays contact information in a grid.
You can download the code and resources for this Try It from the book’s web
page at
www.wrox.com or www.CSharpHelper.com/24hour.html. You can find
them in the Lesson35 folder of the download.
596906c35.indd 401 4/7/10 12:34:52 PM
402
LESSON 35 Programming Databases, Part 1
Lesson Requirements
Start a new project. Download the Contacts.mdb database from the book’s web site and
place it in the project directory.
Add a new data source for this database.
Open the Data Sources window and drag the Contacts table onto the form.
Add code to the
FormClosing event handler to check for unsaved changes.
Hints
Dock the
DataGridView control so it fills the form. Resize the form so all fields are visible.
Step-by-Step
Start a new project. Download the Contacts.mdb database from the book’s web site and
place it in the project directory.
1. This is straightforward.
Add a new data source for this database.
1. Follow the steps described earlier in this lesson.
Open the Data Sources window and drag the Contacts table onto the form.
1. This is straightforward.
Add code to the
FormClosing event handler to check for unsaved changes.
1. Use code similar to the following:
// Check for unsaved changes.
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (this.contactsDataSet.HasChanges())
{
// Make the user conrm.
DialogResult result = MessageBox.Show(
“Do you want to save changes before closing?”,
“Save Changes?”,
MessageBoxButtons.YesNoCancel,
MessageBoxIcon.Question);
if (result == DialogResult.Cancel)
{
// Cancel the close.
e.Cancel = true;
}
else if (result == DialogResult.Yes)
{
// Save the changes.
peopleNamesTableAdapter.Update(peopleDataSet);
596906c35.indd 402 4/7/10 12:34:52 PM
Exercises
403
// Make sure the save worked.
// If we still have unsaved changes, cancel.
e.Cancel = (this.contactsDataSet.HasChanges());
}
// Else the user doesn’t want to save
// the changes so just keep going.
}
}
Please select Lesson 35 on the DVD to view the video that accompanies this lesson.
EXERCISES
1. Make a program similar to the one you built for the Try It except make it display one record at
a time instead of using a grid. Anchor the
TextBoxes so they widen if the form widens. Don’t
forget to enable the Add New and Delete buttons, and to add the
FormClosing event handler.
2. Copy the program you built for this lesson’s Try It. That program’s grid lets the user navigate
through the records, add records, and delete records, so you don’t really need all of those
buttons on the
BindingNavigator. Select the BindingNavigator. In the Properties window,
click the Items property and click the ellipsis to the right. Set the
Visible property to false
for every item except the position, count, and save items.
3. Copy the program you built for Exercise 1. Add a MenuStrip with a Data menu that has
items First, Prev, Next, Last, Add New, Delete, and Save. Set the
Visible property on the
corresponding
BindingNavigator buttons to false.
To make the menu items work, use the
BindingSource’s CurrencyManager. That
object’s properties and methods let you manipulate the current record (hence the
name CurrencyManager). For example, the following code sets the current position
to the first record:
this.contactsBindingSource.CurrencyManager.Position = 0;
Add or subtract one from Position to move to the next or previous record. Set Position to
the
CurrencyManager’s List.Count - 1 value to move to the end of the list.
Use the
RemoveAt method to delete the current record.
Finally, to save changes to the data, write a
SaveChanges method similar to this one:
private void SaveChanges()
{
this.Validate();
this.contactsBindingSource.EndEdit();
this.tableAdapterManager.UpdateAll(this.contactsDataSet);
}
596906c35.indd 403 4/7/10 12:34:53 PM
404
LESSON 35 Programming Databases, Part 1
Invoke this function when the user selects the Save menu item. Also invoke it when the
FormClosing event handler needs to save changes. (The previous version that invokes the
BindingNavigators Save button no longer works because that button is hidden, so it
doesnt do anything.)
You can download the solutions to these exercises from the book’s web page at
www.wrox.com or www.CSharpHelper.com/24hour.html. You can find those
solutions in the Lesson35 folder.
596906c35.indd 404 4/7/10 12:34:53 PM
Click here to Play
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.222.231