* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Download Document
Microsoft SQL Server wikipedia , lookup
Entity–attribute–value model wikipedia , lookup
Concurrency control wikipedia , lookup
Extensible Storage Engine wikipedia , lookup
Open Database Connectivity wikipedia , lookup
Microsoft Jet Database Engine wikipedia , lookup
Functional Database Model wikipedia , lookup
Relational model wikipedia , lookup
Clusterpoint wikipedia , lookup
1 T U T O R I A L 24 Address Book Application Introducing Database Programming 2009 Pearson Education, Inc. All rights reserved. 2 Outline 24.1 24.2 24.3 24.4 Test-Driving the Address Book Application Planning the Address Book Application Creating Database Connections Programming the Address Book Application 2009 Pearson Education, Inc. All rights reserved. 3 Objectives 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 information in databases. 2009 Pearson Education, Inc. All rights reserved. 4 Introduction ■ Sequential-access files are inappropriate for large 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). 2009 Pearson Education, Inc. All rights reserved. 5 24.1 Test-Driving the Address Book Application Application Requirements 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. BindingNavigator ReadOnly Address ID: TextBox Labels and TextBoxes display contact information Find an entry by last name GroupBox Browse All Entries Button Figure 24.1 | Address Book application. 2009 Pearson Education, Inc. All rights reserved. 7 Test-Driving the Address Book Application (Cont.) ■ Click the Move next, Move last, Move previous and Move first Buttons (Fig. 24.2) to navigate through entries. Move first Button Move previous Button Move next Button Move last Button Figure 24.2 | Navigating the entries in the Address Book application. 2009 Pearson Education, Inc. All rights reserved. 8 Test-Driving the Address Book Application (Cont.) ■ 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 Save Data Button Add new Button 0 is placed in Address ID: TextBox Figure 24.3 | Adding an entry in the Address Book application. 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). Email: field updated Figure 24.4 | Editing an entry in the Address Book application. 2009 Pearson Education, Inc. All rights reserved. 10 Test-Driving the Address Book Application (Cont.) ■ 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. 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. Click the Delete Button Figure 24.6 | Deleting an entry in the Address Book application. 2009 Pearson Education, Inc. All rights reserved. 12 24.2 Planning the Address Book Application When the Form loads Display 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 2009 Pearson Education, Inc. All rights reserved. 13 24.2 Planning the Address Book Application (Cont.) 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 Button Display 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 Button If 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 2009 Pearson Education, Inc. All rights reserved. Action/Control/Event (ACE) Table for the Address Book Application 14 ■ Use an ACE table to convert pseudocode into Visual Basic (Fig. 24.7). Action Control Event Label the application’s controls searchLabel, AddressIDLabel, FirstNameLabel, LastNameLabel, EmailLabel, PhoneNumberLabel AddressBookForm Display the first entry in the Load AddressBindingSource AddressBook database AddressBindingNavigatorAddNewItem Add a new entry Click AddressIDTextBox, FirstNameTextBox, LastNameTextBox, EmailTextBox, PhoneNumberTextBox Figure 24.7 | ACE table for the Address Book application. (Part 1 of 3.) 2009 Pearson Education, Inc. All rights reserved. Action/Control/Event (ACE) Table for the Address Book Application (Cont.) Action Update the database with any new, deleted or updated entries Control Event AddressBindingNavigatorSaveItem Click AddressBindingSource, database (object of class AddressBookDataClassesDataContext) AddressBindingNavigatorDeleteItem Delete the current entry 15 Click AddressBindingSource displayed in the Form Click browseAllButton Display the first entry in the AddressBindingSource database and allow the user to browse all entries with the BindingNavigator Clear the search text box searchTextBox Figure 24.7 | ACE table for the Address Book application. (Part 2 of 3.) 2009 Pearson Education, Inc. All rights reserved. Action/Control/Event (ACE) Table for the Address Book Application (Cont.) Action If no entries have a last name that matches the input string, Control Event findButton Click 16 searchTextBox, AddressBindingSource then display empty TextBoxes Otherwise, display the first entry with the specified last name and searchTextBox, AddressBindingSource allow the user to browse through all matching entries with the BindingNavigator Figure 24.7 | ACE table for the Address Book application. (Part 3 of 3.) 2009 Pearson Education, Inc. All rights reserved. Adding a Database Connection to the Address Book Application 17 ■ Create a new Windows Forms Application named 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. 2009 Pearson Education, Inc. All rights reserved. Adding a Database Connection to the Address Book Application (Cont.) 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. Data source type Location of database file Figure 24.8 | Adding a database with the Add Connection dialog. 2009 Pearson Education, Inc. All rights reserved. Adding a Database Connection to the Address Book Application (Cont.) 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). 2009 Pearson Education, Inc. All rights reserved. Adding a Database Connection to the Address Book Application (Cont.) 20 Click to display the database’s tables Right click the Addresses node Select to view the table’s contents Figure 24.9 | Viewing the Addresses table. 2009 Pearson Education, Inc. All rights reserved. Adding a Database Connection to the Address Book Application (Cont.) 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. Fields (columns) Records (rows) Figure 24.10 | Addresses table data. 2009 Pearson Education, Inc. All rights reserved. Adding a Database Connection to the Address Book Application (Cont.) 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. 2009 Pearson Education, Inc. All rights reserved. 23 Modeling the Database with LINQ to SQL Classes ■ 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. 2009 Pearson Education, Inc. All rights reserved. 24 Modeling the Database with LINQ to SQL Classes (Cont.) ■ 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). LINQ to SQL Classes template Figure 24.11 | Adding LINQ to SQL classes. 2009 Pearson Education, Inc. All rights reserved. Modeling the Database with LINQ to SQL Classes (Cont.) 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. Address class created from the Addresses table Properties representing columns in the Addresses Figure 24.12 | Adding a table from the Database Explorer to the Object Relational Designer. 2009 Pearson Education, Inc. All rights reserved. Adding a Data Source to the Address Book Application 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.... 2009 Pearson Education, Inc. All rights reserved. Adding a Data Source to the Address Book Application (Cont.) 27 Add New Data Source Button Add New Data Source link Figure 24.13 | Data Sources window. 2009 Pearson Education, Inc. All rights reserved. Adding a Data Source to the Address Book Application (Cont.) 28 ■ This opens the Data Source Configuration Wizard. ■ Select Object in the wizard (Fig. 24.14) and click Next >. Select Object as the data source type Figure 24.14 | Data Source Configuration Wizard dialog. 2009 Pearson Education, Inc. All rights reserved. Adding a Data Source to the Address Book Application (Cont.) 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. Select the Address class as the object data source Figure 24.15 | Select Address to add a data source that can bind Address information to data-bound controls. 2009 Pearson Education, Inc. All rights reserved. Adding a Data Source to the Address Book Application (Cont.) 30 ■ An Address node now appears in the Data Sources window (Fig. 24.16). Data source name Addresses table’s fields represented in the data source Figure 24.16 | Updated Data Sources window. 2009 Pearson Education, Inc. All rights reserved. 31 Displaying the Address Fields on the Form ■ 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. Address data source Default control for displaying data Select Details to display data in a set of Label–TextBox pairs Figure 24.17 | Selecting a display format for the data. 2009 Pearson Education, Inc. All rights reserved. 32 Displaying the Address Fields on the Form (Cont.) ■ 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. 2009 Pearson Education, Inc. All rights reserved. 33 Displaying the Address Fields on the Form (Cont.) Auto-generated BindingNavigator Auto-generated Labels and TextBoxes to display contact information Auto-generated data binding objects Figure 24.18 | Displaying a table on a Form using a series of Labels and TextBoxes. 2009 Pearson Education, Inc. All rights reserved. 34 Displaying the Address Fields on the Form (Cont.) ■ 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. 2009 Pearson Education, Inc. All rights reserved. 35 Displaying the Address Fields on the Form (Cont.) ■ Reposition the GUI controls to place them in a more natural order, then modify the application’s tab order (Fig. 24.19). Labels and TextBoxes repositioned Figure 24.19 | GUI controls repositioned. 2009 Pearson Education, Inc. All rights reserved. 36 Coding the Form’s Load Event Handler ■ 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. 2009 Pearson Education, Inc. All rights reserved. 37 Coding the Form’s Load Event Handler (Cont.) ■ The FillAll method (Fig. 24.21) defines a LINQ query that retrieves each entry in the Addresses table. 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 Coding the Form’s Load Event Handler (Cont.) ■ Double click the Form to generate its event handler (Fig. 24.22). Figure 24.22 | Retrieving data from the database when the Form loads. 2009 Pearson Education, Inc. All rights reserved. 40 Coding the Form’s Load Event Handler (Cont.) ■ 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. Save Data button disabled Figure 24.23 | Browsing entries in the Address Book application. 2009 Pearson Education, Inc. All rights reserved. Enabling the BindingNavigator’s Save Data Button 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). Validate the Form’s input controls Save changes to the BindingSource Update the database on disk Figure 24.24 | Click event handler for the Save Data Button. 2009 Pearson Education, Inc. All rights reserved. Enabling the BindingNavigator’s Save Data Button (Cont.) 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. 2009 Pearson Education, Inc. All rights reserved. Searching the LastName Field in the AddressBook.mdf Database 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. searchTextBox Find an entry by last name GroupBox findButton searchLabel Figure 24.25 | Add controls to search data by last name. 2009 Pearson Education, Inc. All rights reserved. Searching the LastName Field in the AddressBook.mdf Database (Cont.) 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. 2009 Pearson Education, Inc. All rights reserved. Searching the LastName Field in the AddressBook.mdf Database (Cont.) 45 Figure 24.26 | Retrieving entries with the specified last name. 2009 Pearson Education, Inc. All rights reserved. Adding the Browse All Entries Button and Its Click Event Handler 46 ■ Add a Button named browseAllButton and set its Text property to Browse All Entries (Fig. 24.27). Browse All Entries Button Figure 24.27 | Adding the Browse All Entries Button to the Form. 2009 Pearson Education, Inc. All rights reserved. Adding the Browse All Entries Button and Its Click Event Handler (Cont.) 47 ■ 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 Figure 24.28 | Click event handler for browseAllButton. 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 Outline ■ Figure 24.29 presents the source code for the application. 1 2 3 (1 of 4 ) Public Class AddressBookForm ' create a DataContext to interact with the AddressBook database Private database As New AddressBookDataClassesDataContext() 4 5 6 7 8 9 10 ' load all data from the Addresses table into the BindingSource Private Sub FillAll() Fill the BindingSource with data ' select all rows AddressBindingSource.DataSource = _ Query the Addresses table From entry In database.Addresses _ Order By entry.LastName _ 11 12 13 Select entry End Sub ' FillAll 14 15 ' load data from the database when the Form loads 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 20 DataContext class used to interact with the database Order results by LastName FillAll() End Sub ' AddressBookForm_Load 2009 Pearson Education, Inc. All rights reserved. 50 Outline (2 of 4 ) 21 22 ' saves changes to the database 23 24 Private Sub AddressBindingNavigatorSaveItem_Click( _ ByVal sender As System.Object, ByVal e As System.EventArgs) _ 25 26 Handles AddressBindingNavigatorSaveItem.Click 27 28 29 30 Validate() ' validate input fields AddressBindingSource.EndEdit() ' indicate edits are complete database.SubmitChanges() ' submit the changes to the database 31 ' load all data from the Addresses table 32 33 34 FillAll() 35 36 Validate the Form’s controls Indicate edits are complete Update the database AddressBindingSource.MoveFirst() ' jump to first entry End Sub ' AddressBindingNavigatorSaveItem_Click Move to the first item in the results from the database 2009 Pearson Education, Inc. All rights reserved. 51 Outline (3 of 4 ) 37 ' handles Find Button's Click event 38 Private Sub findButton_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles findButton.Click 39 40 41 42 ' select rows containing the specified last name AddressBindingSource.DataSource = _ 43 44 From entry In database.Addresses _ Where entry.LastName = searchTextBox.Text _ 45 46 Order By entry.FirstName _ Select entry 47 48 49 Fill the BindingSource with data Query the Addresses table Entries with the specified LastName Order results by FirstName AddressBindingSource.MoveFirst() ' jump to first entry End Sub ' findButton_Click 2009 Pearson Education, Inc. All rights reserved. 52 Outline (4 of 4 ) 50 51 52 ' handles Browse All Entries Click event Private Sub browseAllButton_Click( _ 53 54 55 ByVal sender As System.Object, ByVal e As System.EventArgs) _ Handles browseAllButton.Click 56 57 ' load all data from the Addresses table FillAll() 58 59 60 61 AddressBindingSource.MoveFirst() ' jump to first entry searchTextBox.Clear() ' clear the search TextBox End Sub ' browseAllButton_Click 62 End Class ' AddressBookForm 2009 Pearson Education, Inc. All rights reserved.