programming with microsoft visual basic 2008 fourth edition chapter thirteen working with access...
TRANSCRIPT
Programming with Microsoft Visual Basic 2008
Fourth Edition
Chapter Thirteen
Working with Access Databases and LINQ
Previewing the Paradise Bookstore Application
• Open the Chap13\Paradise.exe file
(Need to download Books.accdb Access DB too.)
• Application displays records in the Books database
• Allows the store manager to enter an author’s name (or part of a name) – Displays only books written by the author
• Displays the total value of books in the store
Programming with Microsoft Visual Basic 2008, Fourth Edition 2
GUI Introduction
Previewing the Paradise Bookstore Application (continued)
Programming with Microsoft Visual Basic 2008, Fourth Edition 3
Figure 13-1: Books written by Carol Smith
Lesson A Objectives
After studying Lesson A, you should be able to: • Understand database terms • Connect an application to a Microsoft Access D/B• Bind table and field objects to VB controls• Explain the purpose of VB database objects
– DataSet, BindingSource, – TableAdapter, TableAdapterManager, – BindingNavigator
• Customize a DataGridView control• Handle errors using the Try…Catch statement• Position the record pointer in a dataset
Programming with Microsoft Visual Basic 2008, Fourth Edition 4
Database Terminology
• Computer database: Electronic file containing an organized collection of related information
• Relational database: Database that stores information in tables composed of rows and columns
– Each column (直欄 ) in a table represents a field
– Each row (橫列 ) in a table represents a record
• Field: Single piece of information about an object, e.g., person, place or thing, …
Programming with Microsoft Visual Basic 2008, Fourth Edition 5
Database Terminology (continued)
• Record: A group of related fields that contain all the necessary data about a specific object (person, place, or thing, …)
• Table: A group of similar records
– Each record in a table pertains to the same topic, and contains the same type of information
• Primary key: A field uniquely identifying a record
• Foreign key: Field that links a child record to a parent record in a 1:M relationship
Programming with Microsoft Visual Basic 2008, Fourth Edition 6
Programming with Microsoft Visual Basic 2008, Fourth Edition 7
Figure 13-2: Example of a relational table
Example of a relational table
Programming with Microsoft Visual Basic 2008, Fourth Edition 8
Figure 13-3: Example of PK-FK pair in parent/child tables
Example of PK-FK pair in a 1:M relationship
Connecting an Application to a Microsoft Access Database
• MS Access 2007 database has a file extension of .accdb (Need to install Access 2007 Database Engine Driver in PC)
• Sample database contains one table named tblEmploy, containing employee information
• A VB application must create a database connection to access data
• Data Source Configuration Wizard (資料來源組態精靈 )
– Helps you connect an application to a database
• Dataset: A temporary copy of the data you have requested from the database
Programming with Microsoft Visual Basic 2008, Fourth Edition 9
Programming with Microsoft Visual Basic 2008, Fourth Edition 10
Figure 13-4: Data contained in the tblEmploy table
Connecting an Application to a Microsoft Access Database
(Table example)
Connecting an Application to a Microsoft Access Database
(continued)In Visual Studio, perform the following steps:1. Open the Server Explorer window: Click the View
menu and then click Server (Database) Explorer
2. Click the Data menu and then click Show Data Sources to open Data Sources window
3. Click Add New Data Source button, and then select Database
4. Click New Connection button, and then select Microsoft Access Database File (OLE DB)
5. Click Browse, navigate to database file, and then click Open
Programming with Microsoft Visual Basic 2008, Fourth Edition 11
Connecting an Application to a Microsoft Access Database
(continued)
Programming with Microsoft Visual Basic 2008, Fourth Edition 12
1.2
2.2
3.1
3.2
2.11.1
Connecting an Application to a Microsoft Access Database (Data Source Configuration Wizard)
Programming with Microsoft Visual Basic 2008, Fourth Edition 13
4.1
Connecting an Application to a Microsoft Access Database
• In Visual Studio, perform these steps (continued):
6. Click button on Add Connection screen, and if successful, click Next
(May need to install Access 2007 Database Engine Driver)
7. Click button to include the database file into the current project
8. Click Yes to save connection string
9. On Choose Your Database Objects screen, select all table objects
10.Finish
Programming with Microsoft Visual Basic 2008, Fourth Edition 14
Test Connection
Yes
Programming with Microsoft Visual Basic 2008, Fourth Edition 15
Figure 13-6: Completed Add Connection dialog box
Connecting an Application to a Microsoft Access Database
(Test Connection )
5
4.2
Programming with Microsoft Visual Basic 2008, Fourth Edition 16
Figure 13-7: Message regarding copying the database file
Connecting an Application to a Microsoft Access Database
(continued)
Programming with Microsoft Visual Basic 2008, Fourth Edition 17
Figure 13-8: Save the Connection String to the Application Configuration File screen
Connecting an Application to a Microsoft Access Database
(save connection string)
Programming with Microsoft Visual Basic 2008, Fourth Edition 18
Figure 13-9: Objects selected in the Choose Your Database Objects screen
Connecting an Application to a Microsoft Access Database (Choose Your Database Objects )
Programming with Microsoft Visual Basic 2008, Fourth Edition 19
Figure 13-10: Result of running the Data Source Configuration Wizard
Connecting an Application to a Microsoft Access Database
(continued)
Previewing the Contents of a Dataset
1. Click the form to make it the active window
2. Click Data menu and then click Preview Data to
open Preview Data dialog box
3. Select the object to preview and then click
Preview
4. After previewing the data, click Close button
Check how many new files show up in Morgan
Industries Project
Programming with Microsoft Visual Basic 2008, Fourth Edition 20
Binding the Objects in a Dataset
• Must bind one or more objects in the dataset to
controls in the interface to view dataset contents
• Binding: Connecting a dataset object to a
control
• Bound controls: Connected controls
• Types of controls used to bind dataset objects:
– Computer-created control
– Existing control on the form
Programming with Microsoft Visual Basic 2008, Fourth Edition 21
Programming with Microsoft Visual Basic 2008, Fourth Edition 22
Figure 13-12: Ways to bind an object in a dataset
Binding the Objects in a Dataset (continued)
1 Table Attribute
Having the Computer Create a Bound Control
• When you drag a dataset object onto a form:– Computer creates control (its type is indicated by
icon)
– Dataset object is automatically bound to control
• Example:– Drag tblEmployee table object to the form
– DataGridView control is created to display tabular data, with rows representing records, columns representing fields
• Use list arrow to change the type of control linked to the object
Programming with Microsoft Visual Basic 2008, Fourth Edition 23
Table Attribute
Programming with Microsoft Visual Basic 2008, Fourth Edition 24
Figure 13-13: Icons in the Data Sources window
Having the Computer Create a Bound Control (continued)
Programming with Microsoft Visual Basic 2008, Fourth Edition 25
Figure 13-14: Result of clicking the tblEmploy object’s list arrow
Having the Computer Create a Bound Control (continued)
Programming with Microsoft Visual Basic 2008, Fourth Edition 26
Figure 13-15: Result of clicking the Last_Name object’s list arrow
Having the Computer Create a Bound Control (continued)
Programming with Microsoft Visual Basic 2008, Fourth Edition 27
Figure 13-16: Result of dragging the table object to the form
Having the Computer Create a Bound Control (continued)
Programming with Microsoft Visual Basic 2008, Fourth Edition 28
Figure 13-26: Data displayed in the DataGridView control
Running DataGridView
Having the Computer Create a Bound Control (continued)
• In addition to a control, the computer adds:– BindingNavigator control: To move from one
record to the next in the dataset– TableAdapter object: Connects the database to
the DataSet object; responsible for retrieving data and storing it in the Dataset
– TableAdapterManager object: Handles saving data to multiple tables in the Dataset
– BindingSource object: Provides the connection between the Dataset and the bound controls
Programming with Microsoft Visual Basic 2008, Fourth Edition 29
Programming with Microsoft Visual Basic 2008, Fourth Edition 30
Figure 13-17: Illustration of the relationships among the database, the objects in the component tray, and the bound controls
Having the Computer Create a Bound Control (continued)
located inmemory
located indisk
The DataGridView Control
• DataGridView control: Displays data in a row and column format
• Cell: Intersection of a row and column
• DataGridView’s task list
allows you to add, reorder, and remove columns, and set properties of bound columns
• AutoSizeColumnsMode: Has seven settings that control how the column widths are sized
– Fill setting: Automatically adjusts the column widths so that the display area of the control is filled
Programming with Microsoft Visual Basic 2008, Fourth Edition 31
Programming with Microsoft Visual Basic 2008, Fourth Edition 32
Figure 13-18: Task list for a DataGridView control
The DataGridView Control (continued)
DataGridView’s task list
To set the format of table columns
Programming with Microsoft Visual Basic 2008, Fourth Edition 33
Figure 13-19: Purpose of each task in the DataGridView’s task list
The DataGridView Control (DataGridView’s task list)
常用
常用
Programming with Microsoft Visual Basic 2008, Fourth Edition 34
Figure 13-20: Edit Column dialog box
The DataGridView Control (Edit Column dialog box)
1.1
1.2
2
3.1
Use Header Text to change the title of columns
3.2Use
DefaultCellStyle to set data format
Programming with Microsoft Visual Basic 2008, Fourth Edition 35
Figure 13-21: Completed CellStyle Builder dialog box in DefaultCellStyle
The DataGridView Control (CellStyle Builder)
Programming with Microsoft Visual Basic 2008, Fourth Edition 36
Figure 13-22: DataGridView control after setting some of its properties
The DataGridView Control (continued)
Visual Basic Code
• When a table or field object is dragged onto a
form the computer also enters code in the Code
Editor window
– Code in the form’s Load event uses the
TableAdapter object to retrieve data
– BindingNavigator’s save event is also coded
Programming with Microsoft Visual Basic 2008, Fourth Edition 37
Programming with Microsoft Visual Basic 2008, Fourth Edition 38
Figure 13-23: Code automatically entered in the Code Editor window
Visual Basic Code (continued)
A dataset defined In 資料來源
A table defined incertain dataset
Handling Errors in the Code
• Exception: Error that occurs while an application
is running
• Try…Catch statement: Used to intercept
exceptions and handle them
– Try block: Contains the statements that might fail
– Catch block: Contains the code to handle the
exceptions
Programming with Microsoft Visual Basic 2008, Fourth Edition 39
Programming with Microsoft Visual Basic 2008, Fourth Edition 40
Figure 13-24: Syntax and examples of the Try…Catch statement
Handling Errors in the Code (Try…Catch statement)
Programming with Microsoft Visual Basic 2008, Fourth Edition 41
Figure 13-25: Try…Catch statement entered in the Save Data button’s Click event procedure
Handling Errors in the Code (continued)
Binding to an Existing Control
Can bind an object in a dataset to an existing control on the form in two ways:
•Method 1: Drag object from Data Sources window to control
•Method 2: Set one or more of the control’s properties in the Properties window
– Properties to set depend on the type of control being bound:
• DataGrid: Set DataSource and DataMember
• ListBox: Set DataSource and DisplayMember
• Label or text box: Set DataBindings and Text
Programming with Microsoft Visual Basic 2008, Fourth Edition 42
Coding the Next Record and Previous Record Buttons
• BindingSource object’s Position property:
– Stores an invisible record pointer
– Positions are integer values 0
– First record is at position 0
• BindingSource object’s Move methods: Can be used to move the record pointer in a dataset to the first, last, next, or previous record in the dataset
Programming with Microsoft Visual Basic 2008, Fourth Edition 43
Programming with Microsoft Visual Basic 2008, Fourth Edition 44
Figure 13-29: Syntax and examples of the BindingSource object’s Position property
Coding the Next Record and Previous Record Buttons
(continued)
Programming with Microsoft Visual Basic 2008, Fourth Edition 45
Figure 13-29: Syntax and examples of the BindingSource object’s Position property (continued)
Coding the Next Record and Previous Record Buttons
(continued)
Programming with Microsoft Visual Basic 2008, Fourth Edition 46
Figure 13-29: Syntax and examples of the BindingSource object’s Move methods
Coding the Next Record and Previous Record Buttons
(continued)
Programming with Microsoft Visual Basic 2008, Fourth Edition 47
Figure 13-30: Code entered in each button’s Click event procedure
Coding the Next Record and Previous Record Buttons
(continued)
Lesson A Summary
• Use Data Source Configuration Wizard to connect an application to a database
• Use the Preview Data command on the Data menu to preview the data in a dataset
• Bind an object in a dataset by dragging it to the form and letting the computer create a control, or by dragging it onto an existing control
• Use the Fill setting of the DataGridView’s AutoSizeColumnsMode property to have columns fill the display area
Programming with Microsoft Visual Basic 2008, Fourth Edition 48
Lesson A Summary (continued)
• Use Dock property of DataGridView to anchor it
to the borders of form
• Use BindingSource object’s Position property or
its Move methods to move record pointer while
the application is running
Programming with Microsoft Visual Basic 2008, Fourth Edition 49
Lesson B Objectives
After studying Lesson B, you should be able to:
• Query a dataset using LINQ
LINQ (Language INtegrated Query)
• Add an item to a BindingNavigator control
• Use the LINQ aggregate operators
Programming with Microsoft Visual Basic 2008, Fourth Edition 50
Creating a Query
• Query: Specifies
– the records to select from a dataset, and
– the order in which to arrange the records
• Language Integrated Query (LINQ): A new database query language in Visual Basic 2008
– Where clause: Contains a condition to limit the records to be selected
– Order By clause: Used to arrange the records in ascending or descending order by one or more fields
Programming with Microsoft Visual Basic 2008, Fourth Edition 51
Programming with Microsoft Visual Basic 2008, Fourth Edition 52
Figure 13-32: Basic LINQ syntax and examples for selecting and arranging records
Creating a Query (continued)
Program
Block A
Each record in dataset.table is denoted by variable element in program block A
same record variable name
Programming with Microsoft Visual Basic 2008, Fourth Edition 53
Figure 13-33: Code entered in the Declarations section and btnFind Click event procedure
Creating a Query (continued)
Programming with Microsoft Visual Basic 2008, Fourth Edition 54
Figure 13-33: Code entered in the Declarations section and btnFind Click event procedure (continued)
Creating a Query (continued)
Customizing a BindingNavigator Control
• Can add additional items to a BindingNavigator
control to customize it:
– Button
– Textbox
– Drop-down button
Programming with Microsoft Visual Basic 2008, Fourth Edition 55
Programming with Microsoft Visual Basic 2008, Fourth Edition 56
Figure 13-35: Steps for adding an item to a BindingNavigator control
Customizing a BindingNavigator Control (continued)
Programming with Microsoft Visual Basic 2008, Fourth Edition 57
Figure 13-36: Items Collection Editor dialog box
Customizing a BindingNavigator Control
(Items Collection Editor)An item’s property
Programming with Microsoft Visual Basic 2008, Fourth Edition 58
Figure 13-37: DropDownButton added to the TblEmployBindingNavigator control
Customizing a BindingNavigator Control (continued)
Using the LINQ Aggregate Operators
• Aggregate operator:
Returns a single value from a group of values
• LINQ provides several aggregate operators:
– Average ( )
– Count ( )
– Max ( )
– Min ( )
– Sum ( )
Programming with Microsoft Visual Basic 2008, Fourth Edition 59
Syntax of LINQ Aggregate Operators
Dim variable [As dataType] = Aggregate element In
dataset.table [Where condition] Select element.field
Into aggregateOperator()
Example 1
Dim dblAvgRate As Double _ = Aggregate employee In
EmployeeDataSet.tblEmployee _
Select employee.Rate _ Into Average( )
Programming with Microsoft Visual Basic 2008, Fourth Edition 60
Examples of LINQ Aggregate Operators
Example 2
Dim dblMaxRate As Double _ = Aggregate employee In
EmployeeDataSet.tblEmployee _
Select employee.Rate _ Into Max( )
Example 3
Dim intCounter As Integer _ = Aggregate employee In
EmployeeDataSet.tblEmployee _
Select employee.Emp_Number _ Into Count( )
Programming with Microsoft Visual Basic 2008, Fourth Edition 61
Programming with Microsoft Visual Basic 2008, Fourth Edition 62
Figure 13-40: Message box showing the average pay rate for all employees
Using the LINQ Aggregate Operators (continued)
Lesson B Summary
• Use LINQ to select a range of records in a dataset
• You can customize the BindingNavigator control by adding additional items to it
• LINQ provides aggregate operators that return a single value from a group of values
Programming with Microsoft Visual Basic 2008, Fourth Edition 63
Lesson C Objectives
After studying Lesson C, you should be able to:
• Prevent the user from adding and deleting
records
• Remove buttons from a BindingNavigator control
• Add a label, text box, and button to a
BindingNavigator control
Programming with Microsoft Visual Basic 2008, Fourth Edition 64
Completing the Paradise Bookstore Application
• Requirements for Paradise Bookstore application: – Display records from the Books database– Allow store manager to enter an author’s name (or
part of a name) to display books by that author
• Database contains one table, tblBooks, with 5 fields and 11 records
• User should not be allowed to add or delete records– Must modify the BindingNavigatorControl to
remove the add and delete buttons
Programming with Microsoft Visual Basic 2008, Fourth Edition 65
Completing the Paradise Bookstore Application (continued)
Programming with Microsoft Visual Basic 2008, Fourth Edition 66
Figure 13-41: tblBooks table in the Books database
Completing the Paradise Bookstore Application (continued)
Programming with Microsoft Visual Basic 2008, Fourth Edition 67
Figure 13-42: Completed TblBooksBindingNavigator control
Coding the Paradise Bookstore Application
• Go button’s Click event should display only records whose Author field starts with the characters entered in the txtAuthor text box
– If text box is empty, display all records
– Use the LINQ LIKE operator
• Total Value button’s Click event should display the total value of all books in the store
– Use the LINQ aggregate function SUM
Programming with Microsoft Visual Basic 2008, Fourth Edition 68
Example
Example
Program
Program
Coding the Paradise Bookstore Application (continued)
Programming with Microsoft Visual Basic 2008, Fourth Edition 69
Figure 13-43: Books written by authors whose name begins with s
Click Go1 2enter s
result 3
Coding the Paradise Bookstore Application (continued)
Programming with Microsoft Visual Basic 2008, Fourth Edition 70
Figure 13-44: Message box showing the total value of the inventory
Click Go 1
2result
Programming with Microsoft Visual Basic 2008, Fourth Edition 71
Figure 13-45: Click event procedures for the btnGo and btnTotal controls
Coding the Paradise Bookstore Application (continued)
Lesson C Summary
• Use the DataGridView control’s task box to
prevent the user from adding or deleting records
in the control
• Remove items from the BindingNavigator control
to prevent the user from performing some actions
• Can customize the BindingNavigator control by
adding a label, text box, or button to it
Programming with Microsoft Visual Basic 2008, Fourth Edition 72