Database Programming
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.
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.
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 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:
States table key = StateCode (2-character abbreviation for the state name).
Table Types
Base table – a base table is one that stores basic information about entities – examples
above are the Course and Student tables.
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).
o OLEDB (Object Linking and Embedding Database) – used to connect to all other
database formats – this includes Microsoft Access DBMS.
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.
DataGridView Control
Class exercise
1. Begin a new project – name it kcauniversitydatabases
Font – Size = 9
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
2. Font Size and Bold properties – set as desired (the figure has a 9 point font with Bold =
True).
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).
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.
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.
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:.
Note the new components that were automatically added to the system component tray:
o StudentDetailsDataSet
o StudentBindingSource
o StudentTableAdapter
o TableAdapterManager
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.
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.
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.