0% found this document useful (0 votes)
197 views

Database Programming

This document discusses database programming concepts in Visual Basic .NET, including connecting to and retrieving data from databases. It covers terminology, database concepts like tables and relationships, and using ADO.NET and controls like DataGridView to display database data in forms.

Uploaded by

purityn613
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
197 views

Database Programming

This document discusses database programming concepts in Visual Basic .NET, including connecting to and retrieving data from databases. It covers terminology, database concepts like tables and relationships, and using ADO.NET and controls like DataGridView to display database data in forms.

Uploaded by

purityn613
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 21

Windows Database Programming

Coverage:
This lesson teaches you to store data to and retrieve data from databases. The lesson focuses on
Microsoft Access database; however, the programming techniques covered also work with other
database management systems (DBMS) such as Oracle Corporation's Oracle DBMS and Oracle
databases. You will learn to display data in various Windows-based controls such as TextBox
and DataGridView controls.

In-Class Project
In this lesson you will develop a project for the VB University that enables administrators to
store new student records and retrieve detailed information about courses offered and students
enrolled in courses. You will develop several different forms that retrieve and store data.

The first form displays information from the Course table of the VBUniversity database
through use of a DataGridView control.

Databases and ADO.NET Concepts and Terminology


Terminology – learn these terms:

 Database – a special repository—consists of one or more physical files—used to store


and retrieve data.

 Relational database – a specific type of database where data rows are stored in separate
tables, and the tables are related to each other by key values (see figures showing table
data later in these notes).
 Table – basic database object that stores data – looks like a spreadsheet when you're
viewing data. This figure shows a Student table diagram from a Microsoft SQL Server
database.

Rows and Columns – a table consists of rows and columns.

 Row = a row is a record for an individual course or student.

 Column = a column is a field of data stored for each course such as CourseID, Title,
Department, or for each student such as the StudentSSN, LastName, and FirstName.

 Key Column (Field) – uniquely identifies a row in a table – almost all database tables
require one or more columns that form the key column(s) to identify rows uniquely –
eliminates the occurrence of duplicate rows.

Database Products – VB.NET stores and retrieves data for many different database products
including, but not limited to:

 Oracle (by Oracle Corporation) and DB2 (by IBM) for large systems—these are
competing relational database management systems.

 Microsoft SQL Server for mid-sized systems and larger scalable systems.

 Microsoft Access and other small-sized, individual user or small group systems.

Entities and Relationships – a database stores data about individual entities in separate tables –
example university database entities include Students, Courses, Enrollment (the enrollment of
students in courses), and States.

 This figure shows an entity-relationship diagram for tables in a Microsoft SQL Server
version of the VB University database.
 Relationship – the lines connecting entities represent relationships between the rows in one
table and rows in another table.

 One-to-many relationship – this is the relationship from rows in the Student table to
rows in the Enrollment table (there can be multiple enrollments by students in a course).

o The key symbol represents the one side of the relationship; the infinity symbol
represents the many side of the relationship.

o A student can have many enrollments, but an enrollment row belongs (is
associated) to only one student row.

o The relationship from Course to Enrollment is also one-to-many – a course can


have many enrollments.

o There are other kinds of relationships that you will study in your course on
database modeling and design.

Primary Key Columns –table rows are uniquely identified by one or more primary key
columns. Each table has a different primary key. In the above figure the primary key column
for the various tables are:

 Student table key = StudentSSN (social security number).

 States table key = StateCode (2-character abbreviation for the state name).

 Course table key = CourseID (up to 7-characters identifying a course).

 Enrollment table key = CourseID + StudentSSN + TermCode + YearEnrolled (all


four columns are required to uniquely identify a row in this table since students enroll in
a course more than once. Terms are coded values: SU=Summer; FA=Fall; SP=Spring.

Table Types
 Base table – a base table is one that stores basic information about entities – examples
above are the Course and Student tables.

 Association table – an association table stores information about associations between


entities or information about business transactions – the Enrollment table associates
Course and Student records and the act of enrolling in a course is a business transaction
for the university.

 Validation table – a validation table validates data entered into another table. The
States table is used to validate the value of the StateCode column information entered
for a student row in the Student table.

ADO.NET
VB.NET uses ADO.NET (Active-X Data Objects with .NET technology), a database technology
that supports connection to different database products. ADO.NET:

 Provides the application programming interface between the program application and the
Database Management System that manages the database.

 Stores and transfers data using the Extensible Markup Language (XML).

 Provides four different types of connections to databases across networks:

o SQLClient – used to connect to Microsoft's SQL Server DBMS.

o OracleClient – used to connect to Oracle Corporation’s Oracle DBMS.

o OLEDB (Object Linking and Embedding Database) – used to connect to all other
database formats – this includes Microsoft Access DBMS.

o ODBC (Open Database Connectivity) – used to connect to miscellaneous data


sources.

 ADO.NET supports database access using forms developed for either a Windows or
Web Form environment.

 ADO.NET provides controls that you add to a form that are used to connect to and
manage data in a database table. Columns from a database table are bound to database
controls.

 Controls you can bind include: Label, TextBox, and ComboBox controls as well as
some new controls such as the DataGridView control.
Connecting to a Database or Data Source with VB
This figure shows the steps in setting up a connection to a database or other type of data source.

Configure a binding source. The binding source links to a data source – a data source is usually
a specific database file, but can be another data source such as an array or text file.

 Configure a table adapter. A table adapter handles data retrieval and updating. The table
adapter creates a dataset.

 Create a dataset. A dataset stores data rows that have been retrieved.

 Add controls to the form and set properties of the controls to bind the controls to the columns of
a specific table in the dataset.

 VB will automatically write the code needed to fill a dataset.

DataGridView Control
Class exercise
1. Begin a new project – name it kcauniversitydatabases

2. Set the first form's properties as follows:

 FileName = books grid.vb

 Text = books Grid

 Font – Size = 9

 Font – Bold = True


Displaying Data
3. Access the Data section of the Toolbox in design view. Add a DataGridView control from
the toolbox as shown here.

4. Click the smart arrow tag in the upper right-corner of the DataGridView control – this
displays the DataGridView Tasks window shown in the figure given above.

5. Modify the DataGridView Tasks window as follows:

 Dock property – you can select either the value Fill in the Properties window or click
the Dock in parent container link shown in the figure above – this will cause the control
to fill the form.

 Check the Enable Column Reordering CheckBox.

 Uncheck the Enable Adding, Enable Editing, Enable Deleting –these check boxes that
are checked by default, but we want this form to be read-only.

 Choose Data Source – click the dropdown and select the Add Project Data Source…
hyperlink shown in the figure below – data sources can also be added with the Data
menu.
7. Data Source Configuration Wizard – the wizard displays the Choose a Data Source Type
window, select the Database as a data source type as shown in this figure, then click the Next
button.

8. Choose a Database Model window – click Dataset option and click the Next button.

9. Choose Your Data Connection window – click the New Connection button. Your software
may show an existing connection
10a. Either a Choose Data Source or an Add Connection window will open.

 If a Choose Data Source window is displayed as shown in this figure, we will usually select the
Microsoft Access Database File option. Click Continue.

 If the Add Connection window is open or if you wish to change the type of connection to be
created, then click the Change button. The default Data Source is Microsoft SQL Server
(SqlClient) as shown in the figure below – to add either a SQL Server Database file or MS
Access database file to your project as the data source, click the Change button.

NOTE: change to a Microsoft Access Database File option.

11b. If you are using Microsoft Access:


 The next figure shows the Microsoft Access Add Connection dialog box, click Browse
– locate the database file select it and click Open in the browse window – you will see
the path and database file name added to the Add Connection dialog box as shown in the
figure below.

 The database logon will use the Admin user – no password is necessary for a MS Access
database.

 Click the Test Connection button – if the connection succeeds, you will see a popup
window telling you that the Test connection succeeded. Click OK to close the popup
and OK to close the Add Connection dialog box.

12. Choose Your Data Connection dialog box – you are returned to this window after
selecting the database. Note that the name of the database file has been added to the window.
This window shows an Access database file. Click Next.
13. Visual Studio now asks if you would like the database file (local data file) added to the
project as shown in the Figure 10.13 below. Click Yes.

 Clicking Yes causes the database file to copy to the project folder's root directory making
the project portable so you can take it back and forth to/from work/home/school – however, the
file is copied every time you run the project so any changes you make in terms of adding new
rows, modifying existing rows, or deleting rows will not be made permanently to the copy of the
file without making additional modifications to the properties of the database file

 Clicking No causes the project to point (locate) the file based on the
ConnectionString property setting in its original position – a copy of the database
file is not made in the project.

14. Save the Connection String to the Application Configuration File – defaults to a
selection of Yes – saving the connection string to a configuration file will enable you to change
the string if necessary at a later point in time. Ensure the check box is checked, and then click
Next.
15. Choose Your Database Objects – VB retrieves information from the database file about
the tables and other database objects available for your use. This takes a few moments as shown
in this figure.

15 (continued). Choose Your Database Objects – you must specify the table(s) from which to
retrieve the data to be data displayed by the DataGridView control.

 In this figure, the Tables node is expanded and the Course table is selected.

 Check the Course table checkbox – an alternative is to expand the Course table node and
check just selected columns—not all columns need be selected if they are not needed by
the application user.

 Change the dataset name generated by VB to CourseGridDataSet as shown.

 Click Finish.
16. After the wizard closes, the DataGridView control now has column names from the Course
table as column headings. Also the system component tray displays BindingSource,
TableAdapter, and DataSet objects with names assigned by VB.

Test the Project


Start Debugging – the CourseGrid form will fill with data.

 The form will appear to be similar to the figure shown below.


 You can expand the form to fill the entire computer screen if desired.

 Column sizes can be modified by the application user.

IMPORTANT NOTE: If the form does not display any data and/or you get an error message
The Microsoft.Jet.OLEDB.4.0 provider is not registered on the local machine shown in the
figure below, refer to the section Microsoft Access and Windows 7 Problems provided earlier
in these notes.

Changing the Database File's Properties


When the project runs, if you make changes to the data in the database, it is NOT saved with the
current settings.

 Copy to Output Directory property setting – you must change this property of the
VBUniversity.mdb or VBUniversity.mdf file as shown in the figure below.

 Change from Copy always to Copy if newer – when you make data row changes
(inserts, edits, or deletes) during program execution, the changes will now be saved
because the copy in the \bin\Debug folder will be the newest copy of the database file
and the database file copy in the project root directory will not overwrite the database file
copy in the \bin\Debug folder.

Formatting DataGridView Control Output


You can edit a DataGridView control in order to improve how data is displayed in its data
columns, primarily numeric and date/time data columns.

Format Column Headings and Width

Follow these steps to format column headings and column width.

1. Smart Tag – click the DataGridView control's Smart Tag arrow to display the
DataGridView Tasks window shown in the figure below – click the Edit Columns link as
shown in this figure.

2. Edit Columns window – edit the properties indicated.

3. CourseID Column – set the HeaderText property = Course ID (added a blank space for
readability). DO NOT CHANGE the DataPropertyName property by mistake.

4. Title Column.
 AutoSizeMode property – change from Not Set to None.

 Width property – change to 300 pixels – on startup the column will now display the
entire Title column value.

5. Other Columns – modify the HeaderText property of other columns as indicated:

 CreditHours – Credit Hours

 CourseFees – Course Fees

 DateLastUpdate – Date Last Updated

6. Modify the AutoSizeMode from Not Set to None and Width property to 75 pixels for the
CreditHours , Tuition, and CourseFees columns. Click OK to close the Edit Columns dialog
box.

7. AutoSizeColumnsMode property – an alternative to setting each column's Width property


is to set the DataGridView control's AutoSizeColumnsMode property to a value of AllCells. –

 This will cause all column sizes to vary to match the data displayed.

 Individual columns that have the AutoSizeMode property changed from Not Set to
None and the Width property set to a specific width will retain the specified width – this
will override the DataGridView control’s AutoSizeColumnsMode property setting.

 Close the Edit Columns window. In the Properties window access the
AutoSizeColumnsMode property of the DataGridView control and set the property to
AllCells.

Format Numeric Data Display

To format the display of numeric columns such as the Credit Hours, Tuition, and CourseFees,
open the Edit Columns dialog box again by using the smart arrow tag.
8. Select the Credit Hours column.

 DefaultCellStyle property – click the dialog button (… button) for this property to open
the CellStyle Builder window.

 Format property – click dialog button (… button) for this property to display the
Format String Dialog window – Select Numeric with 2 Decimal places.

 Alignment property in the CellStyle Builder window – choose the MiddleRight


setting.

 Click OK to close the window.

9. Repeat the steps for this column as you did in step 8 for the Tuition and CourseFees
columns.

10. Click OK to close the Edit Columns dialog box. Test the project – make any additional
changes needed in order to achieve a satisfactory display of data. Stop debugging when you
finish testing.

Individual Data Fields – StudentDetails


Form
Binding Data to Other Controls
Another way to display data is with controls such as Label, TextBox and ComboBox controls –
in this design approach, the controls are termed bound controls.

 The form can be designed through use of the Data Sources window – set the data source
to display and drag the data table to the form.
 Data Sources window – access by selecting the Data menu, Show Data Sources menu
item or from the Data Sources tab in the Solution Explorer.

 Can be used to add a new data source to a project.

Add a New Form


1. Project menu, Add Windows Form option – click to add a new form named
StudentDetails.vb.

2. Font Size and Bold properties – set as desired (the figure has a 9 point font with Bold =
True).

3. Text property – set to Student Data – Add, Edit, and Delete.

Add Data Source


4. Select Data menu, Show Data Sources menu item as in the figure below (you can also use
the Server Explorer window to add a new data source).

 You should see the existing CourseGridDataSet.

 For existing data sources, the dataset(s) will display in the Data Sources window as in
this figure along with any tables or views stored in the dataset.

5. Add New Data Source – add a new data source for this form.
 Click the icon shown in this figure (or use the Data menu, Add New Data Source menu
option).

 This causes the Data Source Configuration wizard to display.

6. Data Source Configuration wizard:

 Select the Database icon – click Next.

 Choose a Database Model dialog box – click Dataset and then Next.

 Choose Your Data Connection dialog box – click Next to use the existing connection.

 Choose Your Database Objects dialog box – expand the Tables node as shown in the
figure below – checkmark the Student table – name the dataset object
StudentDetailsDataSet – click Finish.

Adding Bound Controls to the Form


You are ready to add bound controls to the form. You will use a drag/drop approach to build the
form – this is really fast and easy to use. If you mess it up, just delete the form and start over.

7. Data Sources window –


 Expand the DataSet.

 Single-click on the Student table name as shown in the figure below.

 Select the drop-down arrow by the Student table and select Details (if the drop-down
arrow does not display, ensure that the form view for design mode is displayed – not the
coding view).

 Note that the icon for a Details view is different than that for a DataGridView.

8. Point at the Student table name in the Data Sources window – drag/drop the table to the
StudentDetails form to a position about an inch from the top and left margins of the form – the
form will automatically have Label and TextBox controls generated and displayed for each
column in the Student table as shown in this figure.

Note the following:

 The labels have the Text property setting generated automatically by VB – the column
names are automatically divided into prompts appropriate for the form.
o A column named StateCode will generate a label prompt of State Code:.

o A column named Email_Address will generate a label prompt of Email Address:.

 Note the new components that were automatically added to the system component tray:

o StudentDetailsDataSet

o StudentBindingSource

o StudentTableAdapter

o TableAdapterManager

o StudentBindingNavigator – corresponds to the StudentBindingNavigator control


that is automatically added across the top of the form. It has the following
features:

1. Student record (row) counter (1 of 14 in the figure).

2. Move buttons (Move first and Move previous are grayed out in the
figure) such as the Move next button highlighted in the figure next to
the Move last button.

3. Add, Delete, and Save button icons.

 The form will run and execute, but the layout is not very “user-friendly.”

9. Alter the layout by drag/drop the controls on the form as shown in the figure below.

 Adjust the size of the controls as appropriate as shown here.

 Reorder the name to display Last Name, then First Name, then Middle Initial.

 Change the labels as shown on the figure for the Middle Initial (to M), City, State Code,
and Zip Code (to City/State/Zip) and Phone Number (to Phone).

 Tab order – reset to reflect the new arrangement to tab from left-to-right, top-to-bottom.

 AccountBalanceTextBox control – set TextAlign property to Right.


Set the Startup Form/Test the Project

Test the project.

You might also like