chapter thirteen working with access databases and linq programming with microsoft visual basic 2010...

Post on 03-Jan-2016

225 Views

Category:

Documents

3 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Chapter Thirteen

Working with Access Databases and LINQ

Programming with Microsoft Visual Basic 2010

5th Edition

Programming with Microsoft Visual Basic 2010, 5th Edition

Previewing Paradise Bookstore ApplicationOpen the Paradise.exe file Application displays records in the Books

database (data details)Allows store manager entering author’s name

(or part of a name) Displays only books written by the author (data

searching)Displays the total value of books in the store

(data summary)

2

Programming with Microsoft Visual Basic 2010, 5th Edition

Lesson A ObjectivesAfter studying Lesson A, you should be able to: Understand basic database terminologyConnect an application to a Microsoft Access

databaseBind table and field objects to controlsExplain the purpose of the DataSet,

BindingSource, TableAdapter, TableAdapterManager, and BindingNavigator objects

Customize a DataGridView ( 資料方格展示 ) controlHandle exceptions ( 異常 ) using the Try…Catch

statementPosition the record pointer in a dataset

Programming with Microsoft Visual Basic 2010, 5th Edition

Database Terminology

Database in computer An electronic file containing an organized

collection of related information Relational database

A database that stores information in tables composed of rows and columns

Each column in a table represents a fieldEach row in a table represents a record

FieldA single piece of information about a person,

place, or thing

4

Programming with Microsoft Visual Basic 2010, 5th Edition

Database Terminology (cont’d.)

RecordA group of related fields that contain all the

necessary data about a specific person, place, or thing

Table: A group of related recordsEach record in a table pertains to the same topic

and contains the same type of informationPrimary key:

A field uniquely identifying a record Foreign key

A field that links a child record to a parent record

5

example

example

Programming with Microsoft Visual Basic 2010, 5th Edition

Figure 13-4 Example of a 2-table relational database

6

Programming with Microsoft Visual Basic 2010, 5th Edition

Connecting an Application to a Microsoft Access DatabaseMS Access 2007 database has a file

extension of .accdbSample database contains one table named

tblEmploy, containing employee informationMust create a database connection to access

dataData Source Configuration Wizard

Helps you connect an application to a databaseDataset

Temporary copy of the data you have requested from the database

7

example

Programming with Microsoft Visual Basic 2010, 5th Edition

Figure 13-5 Data contained in the tblEmploy table

8

Programming with Microsoft Visual Basic 2010, 5th Edition

Connecting an Application to a Microsoft Access Database (cont’d.)

Open the Solution Explorer window and auto-hide the Properties window

Open the Morgan Industries Solution fileClick the View menu and then click Server

Explorer (Visual Studio) or Database Explorer (Visual Basic Express)

實作練習 : 需下載 Chap13 的 Morgan Industries Solution-DataGridView Access Databases\Employees.accdb

9

Programming with Microsoft Visual Basic 2010, 5th Edition

Connecting an Application to a Microsoft Access Database (cont’d.)

Click the Data on the menu bar and then click Show Data Sources to open Data Sources window

Click Add New Data Source button, and then select Database to open Add Connection window1.Choose type of database (data source)

Click New Connection button, and then select Microsoft Access Database File (OLE DB)

2.Choose file name of databaseClick Browse, navigate to database file, and then click Open

3.Click Test Connection button, and if successful, click Next

實作練習 在第 745~748 頁10

screen

Programming with Microsoft Visual Basic 2010, 5th Edition11

Programming with Microsoft Visual Basic 2010, 5th Edition

Connecting an Application to a Microsoft Access Database (cont’d.)Click Yes to include the database file in the

current project

Click Yes to save connection stringOn Choose Your Database Objects

screen, select tblEmployee table of the Employees.accdb database

12

screen

screen

Programming with Microsoft Visual Basic 2010, 5th Edition

Connecting an Application to a Microsoft Access Database (cont’d.)

Figure 13-7 Message regarding copying the database file

13

Programming with Microsoft Visual Basic 2010, 5th Edition

Connecting an Application to a Microsoft Access Database (cont’d.)

Figure 13-8 Objects selected in the Choose Your Database Objects screen

14

Programming with Microsoft Visual Basic 2010, 5th Edition

Connecting an Application to a Microsoft Access Database (cont’d.)

Figure 13-9 Result of running the Data Source Configuration Wizard

15

Programming with Microsoft Visual Basic 2010, 5th Edition

Previewing the Contents of a DatasetClick the form to make it the active windowClick Data on the menu bar and then click

Preview Data to open Preview Data dialog box

Select the object to preview and then click Preview

After previewing the data, click Close button

實作練習 在第 748~749 頁

16

screen

Programming with Microsoft Visual Basic 2010, 5th Edition

Figure 13-10 Data displayed in the Preview Data dialog box

17

Programming with Microsoft Visual Basic 2010, 5th Edition

Binding the Objects in a Dataset Must bind one or more objects in the dataset

to controls in the interface to view dataset contents

BindingConnecting a dataset object to an interface

controlBound controls

Controls connected to dataset objects Types of controls used to bind dataset objects

Computer-created controlExisting control on the form

18

explanation

Programming with Microsoft Visual Basic 2010, 5th Edition

Figure 13-11 Ways to bind an object in a dataset

19

details

Programming with Microsoft Visual Basic 2010, 5th Edition

Having the Computer Create a Bound ControlWhen you drag a dataset object onto a form:

Computer creates control (its type is indicated by icon)

The dataset object is automatically bound to controlExample

Drag tblEmployee table object from Data Sources window 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

20

result

Data Sources window

example 1

example 2

實作練習 在 第 752 頁

Programming with Microsoft Visual Basic 2010, 5th Edition

Figure 13-12 Icons in the Data Sources window

21

Programming with Microsoft Visual Basic 2010, 5th Edition

Figure 13-15 Result of dragging the table object to the form

22

control name : TblEmployBindingNavigatorSaveItem

Programming with Microsoft Visual Basic 2010, 5th Edition

Figure 13-13 Result of clicking the tblEmploy object’s list arrow

23

Programming with Microsoft Visual Basic 2010, 5th Edition

Figure 13-14 Result of clicking the Last_Name object’s list arrow

24

Programming with Microsoft Visual Basic 2010, 5th Edition

Having the Computer Create a Bound Control (cont’d.)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: Connects the DataSet to the bound controls

25

GUI

relationship among these objects

Programming with Microsoft Visual Basic 2010, 5th Edition

Figure 13-16 Illustration of the relationships among the database, the objects in the component tray, and the bound controls

26

in hard disk

in memory

on GUI

Programming with Microsoft Visual Basic 2010, 5th Edition

The DataGridView ControlDataGridView control

Displays data in a row and column formatCell: Intersection of a row and columnDataGridView’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 sizedFill setting: Automatically adjusts the column

widths so that the display area of the control is filled

27

screen

Programming with Microsoft Visual Basic 2010, 5th Edition

Figure 13-17 DataGridView control’s task list

28

explanation

programmer

user

Programming with Microsoft Visual Basic 2010, 5th Edition

Figure 13-18 Purpose of each task in the DataGridView’s task list

29

screen

Programming with Microsoft Visual Basic 2010, 5th Edition

Figure 13-19 Edit Columns dialog box

30

CellStyle

dialog

Programming with Microsoft Visual Basic 2010, 5th Edition

Figure 13-20 Completed CellStyle Builder dialog box

31

Programming with Microsoft Visual Basic 2010, 5th Edition

Figure 13-21 DataGridView control after setting some of its properties

32

實作練習 在•第 755~756 頁

Programming with Microsoft Visual Basic 2010, 5th Edition

Database Programming in VB

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

33

automatically entered code

Programming with Microsoft Visual Basic 2010, 5th Edition

Visual Basic Code (cont’d.)

Figure 13-22 Code automatically entered in the Code Editor window

34

control & component

relationship among these objects

Programming with Microsoft Visual Basic 2010, 5th Edition

Handling Errors in the CodeException

Error that occurs while an application is running

Try…Catch statementUsed to intercept exceptions and handle

themTry code block

Contains the statements that might failCatch code block

Contains the code to handle the exceptions

35

syntax

Programming with Microsoft Visual Basic 2010, 5th Edition

Figure 13-23 Syntax of the Try…Catch statement (continues)

36

example

Programming with Microsoft Visual Basic 2010, 5th Edition37

Figure 13-23examples of the Try…Catch statement

Programming with Microsoft Visual Basic 2010, 5th Edition

Figure 13-24 Completed Click event procedure for the Save Data button

38

實作練習 在•第 758~760 頁

Programming with Microsoft Visual Basic 2010, 5th Edition

Figure 13-25 Data displayed in the DataGridView control

39

Programming with Microsoft Visual Basic 2010, 5th Edition

Copy to Output Directory Property

Copy to Output Directory property: Determines the way Visual Basic saves changes to local file

Copy always (default setting):Database file is copied to project’s bin\Debug folder each time the application startsResult: database file appears in two different folders Changes to file in bin\Debug folder are overwritten

Copy if newer: Preserves run-time changesCopies over the file in bin\Debug only if it is not current

40

Programming with Microsoft Visual Basic 2010, 5th Edition

Binding to an Existing ControlCan bind an object in a dataset to an existing

control on the form in two ways:Drag object from Data Sources window to controlSet one or more of the control’s properties in the

Properties windowProperties to set depend on the type of control

being bound:DataGridView: Set DataSource propertyListBox: Set DataSource and DisplayMember

properties Label or text box: Set DataBindings /Text

property

41

實作練習•下載 Morgan Industries Soultion-Labels•在第 762~764 頁

Programming with Microsoft Visual Basic 2010, 5th Edition

Coding the Next Record and Previous Record ButtonsBindingSource object’s Position property

Stores an invisible record pointer Positions are integer values 0 First record is at position 0

BindingSource object’s Move methodsCan be used to move the record pointer in a

dataset to the first, last, next, or previous record in the dataset

42

control & componentrelationship among

these objectsexamples

syntax

Programming with Microsoft Visual Basic 2010, 5th Edition

Figure 13-29 Syntax and examples of the BindingSource object’s Position property

43

Programming with Microsoft Visual Basic 2010, 5th Edition

Figure 13-30 Syntax and examples of the BindingSource object’s Move methods

44

Programming with Microsoft Visual Basic 2010, 5th Edition

Figure 13-31 Application’s code

45

實作練習•在第 765~766 頁

Programming with Microsoft Visual Basic 2010, 5th Edition

Lesson A SummaryUse Data Source Configuration Wizard to

connect an application to a databaseUse the Preview Data command on the

Data menu to preview the data in a datasetBind 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

46

Programming with Microsoft Visual Basic 2010, 5th Edition

Lesson A Summary (cont’d.)Use Dock property of DataGridView to

anchor it to the borders of formUse the Try…Catch statement to handle

exceptions (errors) occurring during run time

Use BindingSource object’s Position property or its Move methods to move record pointer while the application is running

47

Programming with Microsoft Visual Basic 2010, 5th Edition

Lesson B ObjectivesAfter studying Lesson B, you should be able

to: Query a dataset using LINQCustomize a BindingNavigator controlUse the LINQ aggregate operators

48

Programming with Microsoft Visual Basic 2010, 5th Edition

Creating a QueryQuery

Specifies the records to select from a datasetthe order in which to arrange the queried records

Language Integrated Query (LINQ)Used to create queries in Visual Basic 2010

Where clauseContains a condition to limit the records to be selected

Order By clauseUsed to arrange the records in ascending or descending order by one or more fields

49

Programming with Microsoft Visual Basic 2010, 5th Edition

Figure 13-32 Basic LINQ syntax and examples

for selecting and arranging records in a dataset

50

Programming with Microsoft Visual Basic 2010, 5th Edition

Figure 13-33 Syntax and an example of assigning a LINQ variable’s contents to a BindingSource object

51

Programming with Microsoft Visual Basic 2010, 5th Edition

Figure 13-35 Employees whose last name begins with the letter S

52

GUI of Morgan Industries Soultion-LINQ

下載 Morgan Industries Soultion-LINQ

實作練習

Programming with Microsoft Visual Basic 2010, 5th Edition

Figure 13-34 Code entered in the General Declarations section and btnFind Click event procedure

53

實作練習•在第 775~777 頁

Programming with Microsoft Visual Basic 2010, 5th Edition

Personalizing BindingNavigator Control

Can add additional items to a BindingNavigator control to personalize itButtonTextboxDrop-down button

54

Programming with Microsoft Visual Basic 2010, 5th Edition

Figure 13-36 Manipulating the items on a BindingNavigator control

55

Items Collection Editor

Programming with Microsoft Visual Basic 2010, 5th Edition

Figure 13-37 Items Collection Editor dialog box56

Programming with Microsoft Visual Basic 2010, 5th Edition

Figure 13-38 DropDownButton added to the TblEmployBindingNavigator control

57

實作練習•下載 Morgan Industries Soultion-Aggregate•在第 777~779 頁

Programming with Microsoft Visual Basic 2010, 5th Edition

Using LINQ Aggregate Operators

Aggregate operatorReturns a single value from a group of values

LINQ provides several aggregate operatorsAverageCountMaxMinSum

58

syntax & example

Programming with Microsoft Visual Basic 2010, 5th Edition

Figure 13-39 Syntax and examples of the LINQ aggregate operators

59

實作練習•在第 780~782 頁

Programming with Microsoft Visual Basic 2010, 5th Edition

Lesson B SummaryUse LINQ to select and arrange records in a

datasetYou can customize the BindingNavigator

control by adding additional items to itLINQ provides aggregate operators that

return a single value from a group of values

60

Programming with Microsoft Visual Basic 2010, 5th Edition

Lesson C ObjectivesAfter studying Lesson C, you should be able

to: Prevent the user from adding and deleting

recordsRemove buttons from a BindingNavigator

controlAdd a label, text box, and button to a

BindingNavigator control

61

Programming with Microsoft Visual Basic 2010, 5th Edition

Complete Paradise Bookstore Application

Requirements for Paradise Bookstore application Display records from the Books databaseAllow store manager to enter an author’s name

(or part of a name) to display books by that author

Database contains one table, tblBooksHas five fields and 11 records

User should not be allowed to add or delete recordsMust modify the BindingNavigatorControl to

remove the add and delete buttons

62

data

GUI

Programming with Microsoft Visual Basic 2010, 5th Edition

Figure 13-42 tblBooks table in the Books database

63

Programming with Microsoft Visual Basic 2010, 5th Edition64

Figure 13-44 Completed TblBooksBindingNavigator control

64

實作練習•下載 Paradise Bookstore Solution•建立使用者介面•在第 787~789 頁

Programming with Microsoft Visual Basic 2010, 5th Edition

Coding Paradise Bookstore Application

Go button’s Click event procedureDisplays only records whose Author field

starts with the characters entered in the text boxIf text box is empty, display all records

Use the LINQ LIKE operatorTotal Value button’s Click event procedure

Displays the total value of all books in the store

Use the LINQ aggregate function SUM

65

GUI

example

example

Programming with Microsoft Visual Basic 2010, 5th Edition

Figure 13-45 Books written by authors whose name begins with s

66

Programming with Microsoft Visual Basic 2010, 5th Edition

Coding the Paradise Bookstore Application (cont’d.)

Figure 13-46 Message box showing the total value of the inventory

67

Programming with Microsoft Visual Basic 2010, 5th Edition

Figure 13-47 Click event procedures

for the btnGo and btnTotal controls

68

實作練習•Buttons Go & Toal Value 的程式•在第 789~791 頁

Programming with Microsoft Visual Basic 2010, 5th Edition

Lesson C SummaryUse 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

69

top related