Tải bản đầy đủ - 0 (trang)
6 Focus on Problem Solving: Karate School Manager Application

6 Focus on Problem Solving: Karate School Manager Application

Tải bản đầy đủ - 0trang

4.6 Focus on Problem Solving: Karate School Manager Application



5. Displays all payments, sorting on any column.

6. Displays a list of payments by one member.

Techniques for completing some of these tasks have been demonstrated in this chapter. Other

tasks will require new skills that will be demonstrated along the way. Before beginning to

write the application, you should consult with the application’s potential users to clarify

some user interface details. We will assume that users want the following:

• For requirement 1, use a DataGridView control.

• For requirement 2, set options that permit modifying and removing rows—the user

will be able to sort by clicking on column headings.

• For requirement 3, create a data input form with TextBox controls and a DateTimePicker control.

• For requirement 4, let the user type a partial last name into a text box. Display a grid

containing all members whose last names begin with the letters entered by the user.

• For requirement 5, join the Members and Payments tables and display the results in a

DataGridView control.

• For requirement 6, display a list of member names (last name, first name) in a ComboBox control; when a member is selected by the user, fill a DataGridView control

with payments by the member.



General Design Guidelines

Each form will have a File menu with a Close window option. A startup form will display a

menu and a program logo. Each major task will be carried out on a separate form to allow

for future expansion. When users see how easy the program is to use, they will surely request

more features.

Before we start to create the application, let’s look at the finished version to get a better idea

of how the detailed steps fit into the overall picture. Professional programmers often create

prototypes or demonstration copies of their programs. The prototype stage is where you can

try different versions of the user interface, which requires some reworking, research, and discussions with customers.

The startup form, named MainForm, displays a program logo and a menu with three main

menu items, shown in Figure 4-49. The startup form should be simple to avoid overwhelming



Figure 4-49 Karate School Manager startup form



209



210



Chapter 4



Using SQL Server Databases



users with details. The menu makes it clear that our system handles two major types of functions: membership and payments. Here are the menu selections:

File

Exit

Membership

List All

Find Member

Add New Member

Payments

All

One Member



Membership Forms

To let users view a list of all members, we have provided the All Members form, shown in

Figure 4-50. The grid allows users to sort on any column, select and delete rows, and modify individual cells within each row. If the user wants to save changes they’ve made back into

the database, they select Save changes from the File menu.

Figure 4-50 All Members form



The Find Member by Last Name form, shown in Figure 4-51, lets the user enter all or part

of a member’s last name. When the user clicks the Go button or presses Enter, a list of

matching member rows displays in the grid. We want name searches to be case-insensitive.

Figure 4-51 Find Member by Last Name form



4.6 Focus on Problem Solving: Karate School Manager Application



The Add New Member form, shown in Figure 4-52, lets the user add a new person to the

Members table. After entering the fields and choosing a date from the DateTimePicker control, the user clicks the Save and Close button. If the user wants to close the form without

saving the data, he or she selects Close without saving from the File menu.



Figure 4-52 Add New Member form



Payments Forms

Now we turn our attention to the Payments subsystem of our application. When the user

selects All from the Payments menu on the startup form, the All Payments form shown in

Figure 4-53 appears. The rows are initially ordered by last name, but the user can sort on

any column by clicking on the column header (once for an ascending sort, twice for a

descending sort).



Figure 4-53 All Payments form



The Payments by One Member form, shown in Figure 4-54, lets the user select a member

name from a ComboBox. The grid fills with the person’s payment history.



211



212



Chapter 4



Using SQL Server Databases



Figure 4-54 Payments by One Member form



From the user’s point of view, the program should be simple. By the time you finish creating

it, you will know how to design a simple user interface, open multiple windows, create

DataSets and connections, search for database rows in various ways, and perform simple

configurations of the DataGridView control.

In Tutorial 4-6, you will create the startup form for the Karate School Manager application.



Tutorial 4-6:

Creating the Karate School Manager startup form

In this tutorial, the form will contain the name of the program, version information, and

a MenuStrip control. This will always be the first form to open and the last form to

close when the application shuts down.

Tutorial Steps

Step 1:



Create a new Windows application named Karate School Manager.



Step 2:



Rename the startup form to MainForm.vb.



Step 3:



Open MainForm and set the following properties: Size = 530, 275; Text =

Karate School Manager; StartPosition = CenterScreen; MaximizeBox = False;

FormBorderStyle = FixedSingle.



Step 4:



Insert a Panel control on the form and set its Size property to 390, 115. Insert

another Panel control inside the first one and set its Size property to approximately 360, 80. Set the BorderStyle property of both panels to Fixed3D.



Step 5:



Insert a Label control inside the smaller panel and set its Text property to

Kyoshi Karate School. We used 26.25-point, bold, italic Monotype Corsiva

font in the example shown earlier in Figure 4-49.



Step 6:



Add another label control near the bottom of the form and set its Text property to Management System 1.0. We used 11.25-point, bold Arial font in our

example.



4.6 Focus on Problem Solving: Karate School Manager Application



Step 7:



Add a MenuStrip control to the form and insert the following menu items:

&File

E&xit

&Membership

&List All

&Find Member

&Add New Member

&Payments

&All

&One Member



Step 8:



Double-click the File / Exit menu item and insert the following code into its

Click event handler:

Me.Close()



Step 9:



Save the project and run the application. Verify that the form closes when you

click the File / Exit menu item.

You’re done for now. Tutorial 4-7 will focus on adding the Membership subsystem to the application.



Tutorial 4-7:

Karate School Manager: Listing all members

In this tutorial, you will use a DataGridView control to list all members in the Karate

school. A new data source will be added to the project, and the DataGridView will be

bound to the data source.

Tutorial Steps

Step 1:



Open the Karate School Manager project, if it is not already open.



Step 2:



Add a new form named AllMembersForm.vb to the project. Set its

MinimizeBox and MaximizeBox properties to False. Set its Text property to

All Members.



Step 3:



In MainForm, create a Click handler for the Membership / List All menu item

and insert the following code:

AllMembersForm.ShowDialog()



Step 4:



In the Data Sources window, select Add New Data Source. Create a connection to the Karate database. In the Choose Your Database Objects window,

select the Members table and name the DataSet as KarateDataSet. Click the

Finish button to save the DataSet.



Step 5:



Place a DataGridView control on the AllMembersForm and name it

dgvMembers. Anchor the grid to all four sides of the form. Set the following

property values: BackGroundColor = Control, BorderStyle = None, RowHeadersVisible = False.



Step 6:



On the same form, open the DataGridView Tasks window. In the Choose

Data Source list, select the Members table from KarateDataSet. Check the



213



214



Chapter 4



Using SQL Server Databases



Enable Editing and Enable Deleting check boxes only. If the grid’s column

headings do not appear as shown Figure 4-55, edit the grid’s Columns property and use the arrow buttons next to the column names list to adjust the column order.



Figure 4-55 Column layout for the Members table



Step 7:



While still editing the Columns property, select the Date_Joined column and

select its DefaultCellStyle property. Enter d into the Format property. (This

format specifies the short date format, in the form m/d/yyyy.) Click the OK

button twice to close the column editor.



Step 8:



Add a MenuStrip control to the form. Add a File menu item, with one subitem:

Close. In the Close item’s Click handler, insert the Me.Close() statement.



Step 9:



Save the project and run the application. From the startup form menu, select

Membership / List All. You should see a list of members, as shown in Figure 4-56,

which is similar to that shown earlier in Figure 4-50.



Figure 4-56 Listing all members



Step 10: End the application.



Using a BindingSource

A BindingSource object creates a connection between a DataSet and the data-bound controls on a form. The BindingSource is attached to the DataSet, and the form’s other controls

are attached to the BindingSource. As the user changes the contents of controls, the BindingSource updates the DataSet.



4.6 Focus on Problem Solving: Karate School Manager Application



The BindingSource class has a DataSource property that exposes the DataSet to which it

is bound. It also has methods that let you add new rows, edit rows, and cancel an editing

operation in progress. Here are some of the more important methods in the BindingSource class:











AddNew—Adds a new row to the list.

RemoveCurrent—Removes the current row from the list.

EndEdit—Applies pending changes to the data source.

CancelEdit—Cancels all changes.



When you bind a control to a data source, a BindingSource object is placed on your form

inside the component tray area (shown in Design view). In Tutorial 4-7, for example, the

DataGridView that displayed the list of members was bound to MembersDataSource. Visual

Studio automatically created a MembersBindingSource object and set the following two

important properties that bound it to the data source:

• DataSource = MembersDataSource

• DataMember = Members

The following are other important BindingSource properties:

• Count—Number of items in the list.

• Current—Returns the object at the current position of the list.

• Filter—An expression that filters the rows.

Let’s look at some examples of these properties and methods. The following statement permits only those members who joined after 1/1/2005 to be displayed:

MembersBindingSource.Filter = ''Date_Joined > '1/1/2005'''



The following statement adds a new empty row to the list of Members:

MembersBindingSource.AddNew()



The following statement removes the current row from the list of members:

MembersBindingSource.RemoveCurrent()



The following statement saves pending changes to the list of members back into MembersDataSource:

MembersBindingSource.EndEdit()



The following statement cancels all pending changes to the list of members:

MembersBindingSource.CancelEdit()



In Tutorial 4-8, you will add an Add Member form to the Karate School Manager program.



T I P : When you double-click a control in the design window for a form, an event handler procedure is generated for you. It always handles the default event for the control.

But it is possible to write handlers for many other events on the same control. Here’s how

you select a different event so you can create a handler:

1. In the Design window, select the control with the mouse.

2. Select the Events button in the Properties window toolbar. It looks like a lightning

bolt.

3. Double-click on the box to the right of the name of the property for which you wish

to create a handler.



215



216



Chapter 4



Using SQL Server Databases



Tutorial 4-8:

Karate School Manager: Adding new members

In this tutorial, you will add a new form to the Karate School Manager program that

lets users add new rows to the Members table. The form will use data binding and write

its changes directly to the database.

Tutorial Steps

Step 1:



Open the Karate School Manager project.



Step 2:



Add a new form to the project named AddMemberForm.vb. Set its Text property to Add New Member. Set the following property values: MaximizeBox =

False; MinimizeBox = False; FormBorderStyle = FixedDialog.



Step 3:



In MainForm, locate the Membership / Add New Member menu item; doubleclick the item and insert the following statement in its Click event handler:

AddMemberForm.ShowDialog()



Step 4:



In the Data Sources window, locate the Members table under the KarateDataSet

entry. Using the dropdown arrow to its right, select Details from the list.



Step 5:



Drag the Members table onto the form. Visual Studio should automatically create data-bound fields and a ToolStrip named MembersBindingNavigator. Set

the Format property of the DateTimePicker control to Short. Use Figure 4-57

as a guide.



Figure 4-57 Add New Member form in Design mode



Step 6:



Delete the MembersBindingNavigator component from the form’s component

tray. Open the form’s code window and delete the MembersBindingNavigatorSaveItem_Click method.



Step 7:



Replace the code in the form’s Load event handler with a statement that calls

AddNew.

MembersBindingSource.AddNew()



The statement clears the form’s input fields and waits for the user to enter data

for a new member.



4.6 Focus on Problem Solving: Karate School Manager Application



Step 8:



Add a MenuStrip control to the form. Add a File menu item with one

subitem: Close. In the event handler for the first item, insert a Me.Close()

statement.



Step 9:



Create a FormClosing event handler for the form and insert the following

statement:

MembersBindingSource.CancelEdit()



This statement cancels any edit operation that might be in progress. The user

might have opened the form, begun to fill in the fields, changed his or her

mind, and decided to close the form.

Step 10: Rename the DateTimePicker control to dtpDate. Also, add the following line



to the form’s Load event handler:

dtpDate.Value = Today



This line is necessary to ensure that the date value will be saved in the database even if the user does not explicitly select a date.

Step 11: Add a button to the form named btnUpdate. Set its Text property to Update.



Create a handler for the button. It calls EndEdit to complete the add new row

operation. Then it calls Update to save the DataSet modifications to the actual

database. Finally, it closes the form, as follows:

Private Sub btnUpdate_Click () Handles btnUpdate.Click

Try

MembersBindingSource.EndEdit()

MembersTableAdapter.Update(KarateDataSet.Members)

Me.Close()

Catch ex As Exception

MessageBox.Show(ex.Message, ''Error'')

End Try

End Sub

Step 12: Save the project and run the application. Click the Membership / Add New



Member menu selection and add a new member. Choose a member ID that

does not appear when you list all members. If you’re not sure, display a list of

all members first.



Using Query Parameters

When SQL queries search for selected records in database tables, you don’t know ahead of

time what values the user might want to find. While it is possible to build a query from an

existing SQL SELECT statement that contains the names of Visual Basic variables, the result

is messy. Suppose, for example, that the user has entered a name in the txtLastName control, and you want to write a query that would locate all rows in the Members table having

the same last name. You can build the following query:

Dim query As String

query = ''SELECT ID, Last_Name, First_Name, Phone, Date_Joined '' _

& ''FROM Members WHERE Last_Name = ''' & txtlastName.Text & '''''



When typing code such as this, it is easy to make a typing mistake, and it can make your

application more vulnerable to software exploits that attempt to access sensitive database

data. A much better approach is to insert a parameter name directly into the SQL query. In



217



218



Chapter 4



Using SQL Server Databases



the following example, a parameter named @Last_Name will be assigned a specific value at

runtime:

SELECT ID, Last_Name, First_Name, Phone, Date_Joined

FROM Members

WHERE Last_Name = @Last_Name



When the TableAdapter’s Fill method is called, we pass it a second argument. That argument

value is automatically assigned to the query parameter:

MembersTableAdapter.Fill(Me.FindMemberDataSet.Members,

txtLastName.Text)



If a query contains more than one parameter, the parameter values become additional arguments for the Fill method. The following query, for example, contains two parameters,

@Last_Name and @Date_Joined:

SELECT ID, Last_Name, First_Name, Phone, Date_Joined

FROM Members

WHERE Last_Name = @Last_Name AND Date_Joined <= @Date_Joined



Notice how the call to the Fill method changes accordingly.

MembersTableAdapter.Fill(Me.FindMemberDataSet.Members,

txtLastName.Text, txtDateJoined.Text)



WildCard Matches in SQL Queries

When searching for matching rows in a database table, you may not always know the exact

value you’re trying to find. SQL has a special keyword named LIKE that uses a wildcard

character to perform partial matches. SQL Server uses the percent sign (%) character to

match any string of characters. For example, the following WHERE clause returns all rows

containing a name starting with the letter G:

WHERE Last_Name LIKE 'G%'



The database returns rows containing last names such as Gomez, Gonzalez, Green, and so

on. By default, the LIKE operator is case-insensitive, so names in lowercase characters still

match G%.

In Tutorial 4-9, you will create a form that lets users search using wildcard characters.



Tutorial 4-9:

Karate School Manager: Finding members by name

In this tutorial, you will create a form for the Karate School Manager application that

lets users search for members using their last names. The query that performs the search

will accept a partial string, so if users do not know the exact spelling of a member name,

they can view a list of members with similar names.

Tutorial Steps

Step 1:



Open the Karate School Manager project.



Step 2:



Add a new form to the project named FindMemberForm.vb. Set its properties as

follows: Text = Find Member by Last Name; MaximizeBox = False; MinimizeBox

= False; StartPosition = CenterScreen; FormBorderStyle = FixedDialog.



4.6 Focus on Problem Solving: Karate School Manager Application



Step 3:



In MainForm, double-click the Membership / Find Member menu item and

insert the following code in its event handler:

FindMemberForm.ShowDialog()



Step 4:



Open FindMemberForm in Design view, add a MenuStrip control to the form,

and create a File submenu with one selection: Close. In its Click event handler,

insert the Me.Close() statement.



Step 5:



Add a Label control, a TextBox named txtLastName, and a Button named

btnGo to the form. Use Figure 4-58 as a guide. (The DataGridView control

will be added in a later step.)



Figure 4-58 The Find Member form in Design mode



Step 6:



Open the KarateDataSet.xsd file, right-click the MembersTableAdapter, select

Add, and then select Query. Insert the following SQL query:

SELECT ID, Last_Name, First_Name, Phone, Date_Joined

FROM Members

WHERE (Last_Name LIKE @name + '%')



After creating the SQL query, click the Next button. In the Choose Methods

to Generate step shown in Figure 4-59, select only the Fill a DataTable option

and name the method FindMember. After you have finished adding the query,

the MembersTableAdapter should appear as in Figure 4-60.

Step 7:



Place a DataGridView control on the form and name it dgvMembers. Set its

properties as follows: BackGroundColor = Control; BorderStyle = None;

Anchor = Bottom, Left, Right; RowHeadersVisible = False.



Step 8:



Using the smart tag in the grid’s upper-right corner, set its data source to the

Members table of KarateDataSet. Disable adding, editing, and deleting of

rows.



Step 9:



Next, you will add a call to the Fill method in the event handler for the button that activates the search. Double-click the Go button and insert the following code in its event handler:

' Perform a wildcard search for the last name.

Me.MembersTableAdapter.FindMember(FindMemberDataSet.Members,

txtLastName.Text)



219



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

6 Focus on Problem Solving: Karate School Manager Application

Tải bản đầy đủ ngay(0 tr)

×
x