52
T U T O R I A L 2009 Pearson Education, Inc. All rights rese 1 24 Address Book Application Introducing Database Programming

Address Book Application Introducing Database Programming

Embed Size (px)

DESCRIPTION

24. Address Book Application Introducing Database Programming. Outline. 24.1 Test-Driving the Address Book Application 24.2 Planning the Address Book Application 24.3 Creating Database Connections 24.4 Programming the Address Book Application. In this tutorial you will learn: - PowerPoint PPT Presentation

Citation preview

T U T O R I A L

2009 Pearson Education, Inc. All rights reserved.

1

24Address Book

ApplicationIntroducing Database

Programming

2009 Pearson Education, Inc. All rights reserved.

2

Outline

24.1 Test-Driving the Address Book Application

24.2 Planning the Address Book Application

24.3 Creating Database Connections

24.4 Programming the Address Book Application

2009 Pearson Education, Inc. All rights reserved.

3

In this tutorial you will learn:

■ Connect to databases.

■ Create LINQ to SQL classes.

■ View the contents of a SQL Server Express database.

■ Add database controls to Windows Forms.

■ Use the Data Sources window.

■ Use LINQ to query a database.

■ Read information from and update informationin databases.

Objectives

2009 Pearson Education, Inc. All rights reserved.

4

■ Sequential-access files are inappropriate forlarge instant-access applications.

■ Instant access is made possible by databases. – Individual database records can be accessed directly

without sequentially searching.– Databases have been used in business applications

for decades.

■ LINQ greatly simplifies manipulating databases, which previously required the use of Structured Query Language (SQL).

Introduction

Application Requirements

2009 Pearson Education, Inc. All rights reserved.

5

24.1 Test-Driving the Address Book Application

You have been asked to create an address book application that stores the first name, last name, e-mail address and phone number of multiple people in a database table. Each entry should be stored as a different row in the table. The user should be able to navigate through the data, add rows, delete rows and save changes to the data. Specific entries should be retrievable by searching the data by last name.

2009 Pearson Education, Inc. All rights reserved.

6

Test-Driving the Address Book Application

■ Run the completed application (Fig. 24.1).

■ The BindingNavigator at the top of the Form is the strip of Buttons below the window’s title bar.

Figure 24.1 | Address Book application.

BindingNavigator

Find an entry by last name GroupBox

Labels and TextBoxes display contact information

Browse All Entries Button

ReadOnly Address ID: TextBox

2009 Pearson Education, Inc. All rights reserved.

7

Test-Driving the Address Book Application (Cont.)

■ Click the Move next, Move last, Moveprevious and Move first Buttons (Fig. 24.2) to navigate through entries.

Figure 24.2 | Navigating the entries in the Address Book application.

Move first Button

Move previous Button

Move next Button

Move last Button

2009 Pearson Education, Inc. All rights reserved.

8

■ Click the Add new Button (Fig. 24.3). – The Address ID: TextBox is automatically filled in with

the value 0.

– Fill in the data fields, then click the Save Data Button

Test-Driving the Address Book Application (Cont.)

Figure 24.3 | Adding an entry in the Address Book application.

Save Data Button

Add new Button

0 is placed inAddress ID: TextBox

2009 Pearson Education, Inc. All rights reserved.

9

Test-Driving the Address Book Application (Cont.)

■ Navigate to the entry for Lisa Black (the first entry).

■ Change the text in the Email: TextBox and save the changes to this entry. (Fig. 24.4).

Figure 24.4 | Editing an entry in the Address Book application.

Email: field updated

2009 Pearson Education, Inc. All rights reserved.

10

■ Enter Brown in the TextBox of the Find an entry by last name GroupBox, then click the Find Button (Fig. 24.5).

■ Note that the BindingNavigator now shows 1 of 2, because there are only two entries with the last name Brown.

Test-Driving the Address Book Application (Cont.)

Figure 24.5 | Browsing entries by last name.

2009 Pearson Education, Inc. All rights reserved.

11

Test-Driving the Address Book Application (Cont.)

■ Navigate to an entry and click the Delete Button(Fig. 24.6).

■ The BindingNavigator now displays 4 of 6 instead of 4 of 7.

Figure 24.6 | Deleting an entry in the Address Book application.

Click the Delete Button

2009 Pearson Education, Inc. All rights reserved.

12

When the Form loadsDisplay the first entry in the AddressBook database

When the user clicks the BindingNavigator’s auto-generated Add new Button

Add a new entry

When the user clicks the BindingNavigator’s auto-generated Save Data Button

Update the database with any new, deleted or updated entries

24.2 Planning the Address Book Application

2009 Pearson Education, Inc. All rights reserved.

13

When the user clicks the BindingNavigator’s auto-generated Delete Button

Delete the current entry displayed in the Form

When the user clicks the Browse All Entries ButtonDisplay the first entry in the database and allow the

user to browse all entries with the BindingNavigator

Clear the search text box

When the user clicks the Find ButtonIf no entries have a last name that matches the input

string,then display empty TextBoxes

Otherwise, display the first entry with the specified last name and allow the user to browse through all matching entries with the BindingNavigator

24.2 Planning the Address Book Application (Cont.)

2009 Pearson Education, Inc. All rights reserved.

14

Action Control Event

Label the application’s controls searchLabel, AddressIDLabel, FirstNameLabel, LastNameLabel, EmailLabel, PhoneNumberLabel

AddressBookForm Load

Display the first entry in the

AddressBook database

AddressBindingSource

AddressBindingNavigator-AddNewItem

Click

Add a new entry AddressIDTextBox, FirstNameTextBox, LastNameTextBox, EmailTextBox, PhoneNumberTextBox

■ Use an ACE table to convert pseudocode into Visual Basic (Fig. 24.7).

Figure 24.7 | ACE table for the Address Book application. (Part 1 of 3.)

Action/Control/Event (ACE) Table forthe Address Book Application

2009 Pearson Education, Inc. All rights reserved.

15

Action Control Event

AddressBindingNavigatorSaveItem Click

Update the database with any

new, deleted or updated entries

AddressBindingSource, database (object of class AddressBook-DataClassesDataContext)

AddressBindingNavigator-DeleteItem

Click

Delete the current entry

displayed in the Form

AddressBindingSource

browseAllButton Click

Display the first entry in the

database and allow the user to

browse all entries with the

BindingNavigator

AddressBindingSource

Clear the search text box searchTextBox

Figure 24.7 | ACE table for the Address Book application. (Part 2 of 3.)

Action/Control/Event (ACE) Table forthe Address Book Application (Cont.)

2009 Pearson Education, Inc. All rights reserved.

16

Action Control Event

findButton Click

I f no entries have a last name that

matches the input string,

then display empty TextBoxes

searchTextBox, AddressBindingSource

Otherwise, display the first entry

with the specified last name and

allow the user to browse through all

matching entries with the

BindingNavigator

searchTextBox, AddressBindingSource

Figure 24.7 | ACE table for the Address Book application. (Part 3 of 3.)

Action/Control/Event (ACE) Table forthe Address Book Application (Cont.)

2009 Pearson Education, Inc. All rights reserved.

17

■ Create a new Windows Forms Applicationnamed AddressBook.

■ Change the name of the source file to AddressBook.vb and change the Form’s Name to AddressBookForm.

■ Change the Form’s Font to 9pt Segoe UI. Then set the Form’s Text property to Address Book.

Adding a Database Connection to theAddress Book Application

2009 Pearson Education, Inc. All rights reserved.

18

■ Select Tools > Connect to Database...– Select Microsoft SQL Server Database File.

– Click Continue to open the Add Connection dialog.

■ Click Browse..., and open the AddressBook.mdf database file.

Adding a Database Connection to theAddress Book Application (Cont.)

Figure 24.8 | Adding a database with the Add Connection dialog.

Data source type

Location of database file

2009 Pearson Education, Inc. All rights reserved.

19

■ Select View > Database Explorer.

■ A database table stores related information in rows and columns.

■ To view the contents of the Addresses table:– Expand the AddressBook.mdf node in the Database

Explorer, then expand the Tables node.

– Right click Addresses, and select Show Table Data (Fig. 24.9).

Adding a Database Connection to theAddress Book Application (Cont.)

2009 Pearson Education, Inc. All rights reserved.

20

Figure 24.9 | Viewing the Addresses table.

Adding a Database Connection to theAddress Book Application (Cont.)

Click to display the database’s

tables

Right click the Addresses node

Select to view the table’s contents

2009 Pearson Education, Inc. All rights reserved.

21

■ Figure 24.10 displays the contents of the Addresses table used in the Address Book application.

■ A record is a table row, and a field is a table column.

Figure 24.10 | Addresses table data.

Fields (columns)

Adding a Database Connection to theAddress Book Application (Cont.)

Records (rows)

2009 Pearson Education, Inc. All rights reserved.

22

■ A table should contain a primary key. – This is a field containing unique values to distinguish

records from one another.

– In this table, the AddressID field is the primary key.

■ Right click the Addresses tab in the IDE and select Close.

Adding a Database Connection to theAddress Book Application (Cont.)

2009 Pearson Education, Inc. All rights reserved.

23

■ LINQ to SQL classes create an in-memory model of your application’s database.

– These classes use ADO.NET technologies to retrieve information from and send information to the database.

– LINQ to SQL classes manage all the ADO.NET code behind the scenes.

Modeling the Database with LINQ to SQL Classes

2009 Pearson Education, Inc. All rights reserved.

24

■ Right click the AddressBook project in the Solution Explorer and select Add > New Item....

– In the Add New Item dialog, select LINQ to SQL Classes and add AddressBookDataClasses.dbml (Fig. 24.11).

Modeling the Database with LINQto SQL Classes (Cont.)

Figure 24.11 | Adding LINQ to SQL classes.

LINQ to SQLClasses

template

2009 Pearson Education, Inc. All rights reserved.

25

■ In the Object Relational Designer expand the AddressBook.mdf node in the Database Explorer.

– Expand the Tables node.

– Drag the Addresses table onto the left pane (Fig 24.12).

– Click Yes in the dialog prompt.

Modeling the Database with LINQto SQL Classes (Cont.)

Figure 24.12 | Adding a table from the Database Explorer to the Object Relational Designer.

Address class created from the Addresses table

Properties representingcolumns in the

Addresses

2009 Pearson Education, Inc. All rights reserved.

26

■ A data-bound control displays information contained in a data source.

– The BindingNavigator and TextBoxes in the completed application are data-bound controls.

■ Open the Data Sources window (Fig. 24.13) by selecting Data > Show Data Sources.

– Click the link Add New Data Source....

Adding a Data Source to theAddress Book Application

2009 Pearson Education, Inc. All rights reserved.

27

Figure 24.13 | Data Sources window.

Add New Data Source Button

Add New Data Source link

Adding a Data Source to theAddress Book Application (Cont.)

2009 Pearson Education, Inc. All rights reserved.

28

■ This opens the Data Source Configuration Wizard.

■ Select Object in the wizard (Fig. 24.14) and click Next >.

Figure 24.14 | Data Source Configuration Wizard dialog.

Select Object as the data source type

Adding a Data Source to theAddress Book Application (Cont.)

2009 Pearson Education, Inc. All rights reserved.

29

■ Expand the AddressBook node and select the Address class as in Figure 24.15 and click Finish.

– If the Address class is not displayed, select File > Save All.

Adding a Data Source to theAddress Book Application (Cont.)

Select the Address class as the object data source

Figure 24.15 | Select Address to add a data source that can bindAddress information to data-bound controls.

2009 Pearson Education, Inc. All rights reserved.

30

■ An Address node now appears in the Data Sources window (Fig. 24.16).

Figure 24.16 | Updated Data Sources window.

Data source name

Adding a Data Source to theAddress Book Application (Cont.)

Addresses table’s fields represented in the data source

2009 Pearson Education, Inc. All rights reserved.

31

■ Open AddressBookForm in Design view, then click the Address node in the Data Sources window (Fig. 24.17).

■ Click the down arrow to view the items in the list. – Select the Details option in the drop-down list to indicate that

the IDE should create a set of Label–TextBox pairs for each field.

Displaying the Address Fields on the Form

Address data source

Figure 24.17 | Selecting a display format for the data.

Default control for displaying data

Select Details to display data in a set of Label–TextBox pairs

2009 Pearson Education, Inc. All rights reserved.

32

■ Drag the Address node from the Data Sources window to the Form.

– The IDE creates a series of Labels and TextBoxes (Fig. 24.18).

– The IDE also creates a BindingNavigator and a BindingSource.

Displaying the Address Fields on the Form (Cont.)

2009 Pearson Education, Inc. All rights reserved.

33

Figure 24.18 | Displaying a table on a Form using a series of Labels and TextBoxes.

Auto-generated BindingNavigator

Auto-generated databinding objects

Displaying the Address Fields on the Form (Cont.)

Auto-generated Labelsand TextBoxes to display

contact information

2009 Pearson Education, Inc. All rights reserved.

34

■ The AddressID is used to uniquely identify each record, so users should not be allowed to edit its value.

– Set the Address ID: TextBox’s ReadOnly property to True.

– Also set its TabStop property to False.

Displaying the Address Fields on the Form (Cont.)

2009 Pearson Education, Inc. All rights reserved.

35

Figure 24.19 | GUI controls repositioned.

Displaying the Address Fields on the Form (Cont.)

Labels and TextBoxes repositioned

■ Reposition the GUI controls to place them in a more natural order, then modify the application’s tab order (Fig. 24.19).

2009 Pearson Education, Inc. All rights reserved.

36

■ Line 3 (Fig. 24.20) refers to AddressBookDataClassesDataContext— defined as part of the LINQ to SQL classes.

■ This object has properties representing each table you added to the AddressBookDataClasses LINQ to SQL classes.

Figure 24.20 | Creating a DataContext object.

Coding the Form’s Load Event Handler

2009 Pearson Education, Inc. All rights reserved.

37

■ The FillAll method (Fig. 24.21) defines a LINQ query that retrieves each entry in the Addresses table.

Coding the Form’s Load Event Handler (Cont.)

Figure 24.21 | Retrieving data from the database using LINQ.

2009 Pearson Education, Inc. All rights reserved.

38

Coding the Form’s Load Event Handler (Cont.)

■ The From clause specifies the data source.

■ The AddressBookDataClassesDataContext object handles all the details of querying the database.

■ The LINQ clause Order By sorts the query results according to the property specified after the Order By keywords.

2009 Pearson Education, Inc. All rights reserved.

39

■ Double click the Form to generate its event handler (Fig. 24.22).

Figure 24.22 | Retrieving data from the database when the Form loads.

Coding the Form’s Load Event Handler (Cont.)

2009 Pearson Education, Inc. All rights reserved.

40

■ Run the application (Fig. 24.23).

■ As you browse the entries, notice that they are sorted alphabetically by last name.

■ The Save Data Button in the BindingNavigator is disabled.

Figure 24.23 | Browsing entries in the Address Book application.

Coding the Form’s Load Event Handler (Cont.)

Save Data button disabled

2009 Pearson Education, Inc. All rights reserved.

41

■ Set the Save Data Button’s Enabled property to True.

■ Double click the Save Data Button to create its Click event handler (Fig. 24.24).

Figure 24.24 | Click event handler for the Save Data Button.

Enabling the BindingNavigator’sSave Data Button

Validate the Form’s input controls

Save changes to the BindingSource

Update the database on disk

2009 Pearson Education, Inc. All rights reserved.

42

■ The Validate method validates any of the controls on the Form that implement Validating or Validated events.

■ The EndEdit method ensures that the data source is updated with any changes made by the user.

■ The SubmitChanges method writes the changes to the SQL Server database on disk.

■ The BindingSource’s MoveFirst method to move to the first entry.

Enabling the BindingNavigator’sSave Data Button (Cont.)

2009 Pearson Education, Inc. All rights reserved.

43

■ Add to the Form a Label named searchLabel, a TextBox named searchTextBox and a Button named findButton (Fig. 24.25).

■ Place these controls in a GroupBox named findByLastNameGroupBox.

Figure 24.25 | Add controls to search data by last name.

searchTextBox

searchLabel

Find an entry by last name GroupBox

Searching the LastName Field in the AddressBook.mdf Database

findButton

2009 Pearson Education, Inc. All rights reserved.

44

■ Double click the Find Button to create its Click event handler (Fig. 24.26).

■ A LINQ query retrieves entries where the last name matches the name specified in searchTextBox.

■ Because all entries returned by this query have the same last name, the results are ordered the by first name.

Searching the LastName Field in the AddressBook.mdf Database (Cont.)

2009 Pearson Education, Inc. All rights reserved.

45

Figure 24.26 | Retrieving entries with the specified last name.

Searching the LastName Field in the AddressBook.mdf Database (Cont.)

2009 Pearson Education, Inc. All rights reserved.

46

Figure 24.27 | Adding the Browse All Entries Button to the Form.

Adding the Browse All Entries Buttonand Its Click Event Handler

■ Add a Button named browseAllButton and set its Text property to Browse All Entries (Fig. 24.27).

Browse All Entries Button

2009 Pearson Education, Inc. All rights reserved.

47

Figure 24.28 | Click event handler for browseAllButton.

Adding the Browse All Entries Buttonand Its Click Event Handler (Cont.)

■ Double click the Browse All Entries Button to create its Click event handler (Fig. 24.28).

Refill the AddressBindingSource with all

address entries

Jump to the first entry

Clear the searchTextBox

2009 Pearson Education, Inc. All rights reserved.

48

Testing Your Completed Address Book Application

■ Enter a new contact, fill in the fields, then click the Save Data Button.

■ Next, search for the last name of the contact that you entered, using searchTextBox and findButton.

■ Now click the Browse All Entries Button.

■ Test the delete function by deleting an entry and then clicking the Save Data Button.

2009 Pearson Education, Inc. All rights reserved.

49

1 Public Class AddressBookForm

2 ' create a DataContext to interact with the AddressBook database

3 Private database As New AddressBookDataClassesDataContext()

4

5 ' load all data from the Addresses table into the BindingSource

6 Private Sub FillAll()

7 ' select all rows

8 AddressBindingSource.DataSource = _

9 From entry In database.Addresses _

10 Order By entry.LastName _

11 Select entry

12 End Sub ' FillAll

13

14 ' load data from the database when the Form loads

15 Private Sub AddressBookForm_Load(ByVal sender As System.Object, _

16 ByVal e As System.EventArgs) Handles MyBase.Load

17

18 ' load all data from the Addresses table

19 FillAll()

20 End Sub ' AddressBookForm_Load

■ Figure 24.29 presents the source codefor the application.

Outline

(1 of 4 )

DataContext class used to interact with the database

Query the Addresses table

Order results by LastName

Fill the BindingSource with data

2009 Pearson Education, Inc. All rights reserved.

50

21

22 ' saves changes to the database

23 Private Sub AddressBindingNavigatorSaveItem_Click( _

24 ByVal sender As System.Object, ByVal e As System.EventArgs) _

25 Handles AddressBindingNavigatorSaveItem.Click

26

27 Validate() ' validate input fields

28 AddressBindingSource.EndEdit() ' indicate edits are complete

29 database.SubmitChanges() ' submit the changes to the database

30

31 ' load all data from the Addresses table

32 FillAll()

33

34 AddressBindingSource.MoveFirst() ' jump to first entry

35 End Sub ' AddressBindingNavigatorSaveItem_Click

36

Outline

(2 of 4 )

Indicate edits are complete

Update the database

Validate the Form’s controls

Move to the first item in the results from the database

2009 Pearson Education, Inc. All rights reserved.

51

37 ' handles Find Button's Click event

38 Private Sub findButton_Click(ByVal sender As System.Object, _

39 ByVal e As System.EventArgs) Handles findButton.Click

40

41 ' select rows containing the specified last name

42 AddressBindingSource.DataSource = _

43 From entry In database.Addresses _

44 Where entry.LastName = searchTextBox.Text _

45 Order By entry.FirstName _

46 Select entry

47

48 AddressBindingSource.MoveFirst() ' jump to first entry

49 End Sub ' findButton_Click

Outline

(3 of 4 )

Fill the BindingSource with data

Query the Addresses table

Entries with the specified LastName

Order results by FirstName

2009 Pearson Education, Inc. All rights reserved.

52

50

51 ' handles Browse All Entries Click event

52 Private Sub browseAllButton_Click( _

53 ByVal sender As System.Object, ByVal e As System.EventArgs) _

54 Handles browseAllButton.Click

55

56 ' load all data from the Addresses table

57 FillAll()

58

59 AddressBindingSource.MoveFirst() ' jump to first entry

60 searchTextBox.Clear() ' clear the search TextBox

61 End Sub ' browseAllButton_Click

62 End Class ' AddressBookForm

Outline

(4 of 4 )