VBU 8 -Windows Database Programming
VBU 8 -Windows Database Programming
INTRODUCTION
In this chapter 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.
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. The current API is ADO.NET 4.
• 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.
The approach you take to fixing this problem depends on whether you
are running Visual Studio Ultimate Edition or the Visual Basic Express
Edition.
Visual Studio Ultimate Edition Fix
Use this procedure if you are running Visual Studio Professional
Edition. In order to connect to an Access database when running Visual
Studio on a 64-bit machine, you need to specify for Visual Studio to use
32-bit mode. Follow these steps to eliminate this error:
2. Click the Compile tab along the left side of My Project -- the figure
shown below will display.
3. Click the Advanced Compile Options... button to display
the Advanced Compiler Settings dialog box.
4. Click the Target CPU drop-down arrow and select the x86 target --
this will allow your program to run in 32-bit mode.
Visual Basic Express Edition Fix
Use this procedure if you are running Visual Basic Express Edition. In
order to connect to an Access database when running Visual Studio on
a 64-bit machine, you need to specify for Visual Studio to use 32-bit
mode; however, the above procedure will not work because the
Advanced Compiler Settings window will not display a Target CPU drop-
down box. Instead, you will need to carefully modify the project file
using a text or XML editor.
3. Navigate (browse) to the project directory, and highlight the project file
(the file is inside the solution folder for your project and ends in the
filename extension of .vbproj as shown in this figure). After
highlighting the project file, click the Open button.
4. After opening the file, it should display (open) in an XML editor
window.
5. Locate the first <PropertyGroup> section and add the following line:
<PlatformTarget>x86</PlatformTarget>
6. Save the project (.vbproj) file. You can now reopen the project—use
the File menu, Open Project option to browse for the project folder
and click the solution file (.sln) to open the project, and continue with
your debugging and testing.
You may wish to experiment on your home PC with SSE. There are
potential SSE problems. Although the problems are rare, they usually
arise because SSE uses a logging file to track of transaction
modifications to the database (the .ldf file). If you receive error
messages while trying to access a SSE database file or while executing
code that should connect to an SSE database, you can try to resolve the
problem by restarting the SSE Windows service that runs the database
engine as follows:
• Start
• Control Panel
• If you are using Category View, select Performance and
Maintenance
• Administrative Tools
• Services
• Click on SQL Server (SQLEXPRESS)
• Click on Restart
• Try again to access the file in Visual Studio
1. Copy the one of these databases from the drive Y: network server to
the My Documents folder.
2. Begin a new project – name it Ch10VBUniversity.
3. Set the first form's properties as follows:
• FileName = CourseGrid.vb
• Text = Course Grid
• Font – Size = 9
• Font – Bold = True
Displaying Data
4. Access the Data section of the Toolbox in design view. Add
a DataGridView control from the toolbox as shown here.
10b. Change Data Source window – this window may display next
depending on the type of database you copied from drive Y: (either MS
SQL Server Express or MS Access). The appearance of the window is
different for different data sources. You may want to change the data
source by clicking the Change button to change to Microsoft Access.
• 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.
Each time the program executes, the original root folder copy of the
database is again copied to \bin\Debug folder – thus the changes made
to the data are lost from any previous execution runs.
End Sub
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.
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.
VB University Project – StudentGrid Form
This section provides you additional practice using the DataGridView
control. Build a form like the one shown in this table to display student
information by using a DataGridViewcontrol.
4. Click the smart arrow tag of the DataGridView control to display the
DataGridView Tasks window.
• Dock the DataGridView control to fill the entire form.
• Enable column reordering, but disable adding, editing, and
deleting data rows.
5. Choose a data source – use the existing data connection when the
wizard displays the Choose Your Data Connection dialog box.
• Work through the wizard. In the Choose Your Database
Objects dialog box select the Student table.
• Name the dataset StudentGridDataSet.
• Click Finish – when the wizard closes, observe the new objects in
the system component tray and the columns displayed in the
DataGridView control.
6. Resize the form to make it large enough to display most of the data
columns.
7. Open the coding window for the form and modify the Load event to
add a Try-Catch block like the one shown here.
9. Click the smart arrow tag to open the Edit Columns link. Use the
Edit Columns dialog box to:
• Set the HeaderText property – change selected columns to the
values indicated:
o StudentSSN – SSN
o FirstName – First Name
o LastName – Last Name
o MiddleInitial – Mi
o StateCode – State
o ZipCode – Zip
o PhoneNumber – Telephone
o EmailAddress – Email
o AccountBalance – Account Balance
This figure shows the .xsd schema file for the StudentGrid form in
the Solution Explorer window – double-clicking the file will display the
schema in visual format. The visual format shows:
• the primary key column(s).
• other column names.
• multiple tables and their relationships when more than one
table has data displayed.
• the table adapter (StudentTableAdapter at the bottom of
the Student image) – selecting this displays properties that
include the CommandText property that stores the SQL
statement used to select data from the Student table.
XML is an industry-standard format used to store and transfer data.
XML data is stored as plain text identified by tags like HTML tags. You
can edit an XML file with a plain text editor such as Notepad, and the
data can be transferred through Internet firewalls.
An XML schema file can also be used to describe fields (columns), data
types, and any constraints such as fields that are required. Each
VB.NET project that connects to a database has an XML schema
file. The data in the XML data file is validated against the data
definitions in the XML schema file.
App.Config File
Recall that earlier you directed the system to generate a configuration
file. The code shown below is that generated and stored in
the App.Config file found in the Solution Explorerwindow.
You will learn how to build a third form for the project like the one shown
here.
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).
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.
Sorting Data
The data displayed in the form is not sorted.
There are several ways to change the sorted display of data. This
describes one approach.
2. In the Properties window select the Sort property – type the name of
the column or columns to be used to sort data in the dataset – the
column name(s) entered must EXACTLYmatch those in the dataset.
• The figure below shows sorting by LastName and
then FirstName column name values.
• Enter the property value as LastName, FirstName – do not forget
the comma between the column names.
3. Run the project and confirm that the data is sorted by last name and
then first name within last name.
3. Set the Mask property by opening the Input Mask window (click
the … dialog box button) and select Phone number for a mask.
The new MaskedTextBox will not display any data because the
control is not bound to the DataSource.
The approach you will learn here changes the default configuration as
follows:
• Make Bound Controls ReadOnly – each bound control on the
form will have ReadOnly = True – this will prevent changing any
data row values.
• Add an Edit Button – edit operations will begin by having the
application user click an Edit Button on the BindingNavigator
control – since there is no Edit Button on the control, one will need
to be added.
• Add a Cancel Button – a Cancel Button will need to be added to
the BindingNavigator control in the event that the application user
decides not to edit a data row or clicks the Edit Button by accident.
• Disable Cancel and Save Buttons – both of these buttons needs
to be disabled while viewing records – their Enabled property
= False; during Add and Edit operations set Enabled = True for
both of these buttons.
• Alter the BindingNavigator Control Interface – during Edit
operations, all items on the BindingNavigator control except
the Save and Cancel Buttons will be disabled by making them
invisible – set Visible = False.
• When the operation is either saved or canceled, the values
of ReadOnly and Visible will be reversed.
Add this sub procedure to your program. Check that the control names
on your form match the names used in the sub procedure.
Add this sub procedure to your program. Check that the control names
on your form match the names used in the sub procedure.
The code generated by VB for the Save button of the binding navigator
control is very simple and does not catch exceptions. The code is
shown here.
Catch ex As Exception
Dim MessageString As String = "Report
this error to the system administrator: " &
ControlChars.NewLine & ex.Message
Dim TitleString As String = "Error During
Save Operation"
MessageBox.Show(MessageString,
TitleString, MessageBoxButtons.OK,
MessageBoxIcon.Error)
End Try
End Sub
The UpdateAll method is fairly complex and is more useful than the
older Update method that was previously used to update datasets.
• Updates are performed on a row-by-row basis – this means that
if multiple DataSet modifications (either Insert, Update, or Delete
operations), then you would need to control the order of the
updates.
• Using the TableAdapterManager ensures that updates involving
multiple tables are processed in the correct order where the order
of the updates is important.
• The code you're learning in this note set only allows a single
update operation to take place at a time – if the database rejects
the update, then it is easier to handle the OleDbException that is
thrown by the database back to your application with a Try-Catch
block.
• The Structured Query Language commands to execute the
required INSERT, UPDATE, or DELETE statements on the
database are generated automatically by Visual Studio and
the UpdateAll method automatically selects the correct command
to pass to the database.
• When an UpdateAll method fires,
the TableAdapterManager examines each data
row's RowState property in order to execute the
required INSERT, UPDATE, or DELETEstatements.
• After a successful update, changes to the data row are accepted
within the DataSet – this makes it unnecessary to call
the AcceptChanges method of the DataSet object.
Test the project.
• Run the project, select a data row to edit, and click
the Edit Button.
• Make a change to the data (such as the student's Major field of
study) and click the Save button.
• Shutdown the application, then start it back up again – you should
find that the data row was saved with the new data value.
Calling the SetControls sub procedure with a value of False will ensure
that neither of the above conditions can occur because during an Add
Operation the Add New button and all Move buttons are invisible.
'Set focus
SSNMaskedTextBox.Focus()
End Sub
Try
Dim ResponseDialogResult As DialogResult
= MessageBox.Show("Confirm to delete the student
record.", "Delete Y/N?", MessageBoxButtons.YesNo,
MessageBoxIcon.Question,
MessageBoxDefaultButton.Button2)
If ResponseDialogResult =
Windows.Forms.DialogResult.Yes Then
'Delete the row by removing the
current record,
'ending the edit, and calling the
Update method
StudentBindingSource.RemoveCurrent()
StudentBindingSource.EndEdit()
TableAdapterManager.UpdateAll(Student
DetailsDataSet)
End If
Catch ex As Exception
'Some other exception was triggered
MessageBox.Show("Unexpected error in
delete operation: " & ControlChars.NewLine &
ex.Message, "Delete Operation Error",
MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
• If the deletion fails, the line of code generating the exception will
usually be the line of code with the UpdateAll method. This
triggers an OleDbException that is caught by the first of
two Catch blocks. The OleDbException is raised when a deletion
fails due to referential integrity constraints:
o A message box displays an appropriate message.
o The DataSet's RejectChanges method is used to reject the
deletion in the DataSet – essentially this undeletes the
deleted row that the database rejected.
o The BindingSource's Position property is reset to the
record number of the data row for which deletion failed.
Data Validation
Additional Exception Handling
A program can be improved through the use of techniques to ensure
data values entered during Edit and Add operations are valid.
• You have learned to use a ValidData function to validate data
entry
• This chapter also requires you to write a ValidData function to
validate data. A good practice is to use a ValidData function to
validate data entered for a new record or modified for an existing
record prior to executing an UpdateAll method to modify the
database.
• You can replace the Me.Validate command generated for
a Save button with the BindingNavigator control with a call to
a ValidData function.
ValidData Function
Initially the code sets the function name ValidData = False – this
assumes that some of the data is not valid.
• Each business rule is tested.
• If a rule fails, an error message is displayed and control passes to
the End If at the bottom of the function and the function exits
returning a value of False. This approach ensures that only one
error message at a time will display.
• If all business rules are satisfied, the Else branch executes
setting ValidData = True and the function exits returning a value
of True.
• Note the use of Focus and SelectAll methods to make the
program more user-friendly.
The initial If statement tests the first validation rule – SSN must be 11
characters.
• The MaskCompleted method of the MaskedTextBox determines
if the controls is full of numbers – no blanks, none missing.
MaxLength Property
One of the easiest ways to enforce validation rules regarding the
maximum length (size) of data to be stored to a particular column in a
table is by setting the MaxLength property of a control such as a
TextBox.
• MaxLength property – limits the number of characters that can be
typed into a control.
• Example: the value entered for StateCodeTextBox cannot be
larger than 2 characters such as CA for California or IL
for Illinois. You should set the MaxLength property of
the StateCodeTextBox control to 2.
MaxLength should be set for each control that stores data to be saved
to the database as follows:
• String data. If the control (a TextBox or label) displays string
data, you can examine the database table in design mode and
determine the maximum allowed length for values to be
stored/displayed in the control.
• Numeric data. For numeric data, you need to use good judgment
or determine what rules the business wishes to enforce.
o Example #1: a TextBox control that displays the number of
credit hours for which a student can enroll may be limited to
a maximum value of 12 hours if the University does not offer
courses for more than that number of credit hours (some
School of Education student teaching classes may be taken
for up to 12 credits per term) – since 12 hours is the
maximum credit hours for a course and two characters are
sufficient to store the largest value, set the MaxLength for
this TextBox to 2.
o Example #2: You need to store a currency value such
as $99,999.00. You need to allow characters for the
display/storage of the dollar sign, comma and decimal
point. This particular value is 10 characters at a maximum.
• Date/Time data. For date/time data, do not worry about enforcing
a maximum length – date/time values are stored in a database as
data that are a fixed length in size.
This event validates the keystrokes for a TextBox or other type of control
such as a ComboBox.
• Example: the AccountBalanceTextBox control for
the STUDENT table should only store numbers, a decimal point, a
comma, and a currency symbol (we will use a $ assuming US
currency) – example account balance: $1,542.98.
• The application user must also be able to use the backspace key
to delete erroneous entries.
• The event should restrict keystrokes that are accepted into
the TextBox to numbers (Asc values 48 to 57), a decimal point
(Asc value 46 ), a comma (Asc value 44 ), the dollar sign
(Asc value 36), and the backspace key (Asc value 8).
• Note that the Key_Press event does not trap the
keyboard’s delete key and arrow keys.
If you have not already done so, modify your project as follows:
• Code a ValidData function and Key_Press event sub procedure.
• Set the MaxLength property of the appropriate TextBox controls.
• Set the CharCasing property of
the StateCodeTextBox to Upper.
• Modify the Save button’s Click event sub procedure
• Test the program by trying to enter invalid data.
Use a ComboBox to display the student last name or SSN value and
then when a value is selected from the ComboBox, display the
corresponding values in the other bound controls on the form.
3. Check the Use data bound items check box as shown in the figure
below – this causes the Data Binding Mode properties to display as
shown in the figure:
o DataSource – StudentBindingSource.
o DisplayMember – LastName.
o ValueMember – StudentSSN.
'Enable/disable ComboBox
LastNameComboBox.Enabled = ValueBoolean
A State ComboBox
The States table of the VBUniversity database is a validation table. It
has two columns:
• StateCode – stores the two character abbreviation code.
• StateName – stores the full name of a state.
Add a ComboBox
1. Delete the existing StateCodeTextBox control.
Add a DataSource
4. Click the StateComboBox Smart Arrow Tag as shown in the figure
below.
5. Check the Use data bound items CheckBox as shown in the figure
blow.
6. Select the Data Source drop-down arrow and then click the Add a
Project Data Source link.
• These four property settings enable you to display data from one
column of a validation table (here this is the States table), and
save a value from another column of a validation table to a column
of a table in another data source (here this is
the Student table, StateCode column).
• The value actually saved to an edited or new Student table row is
the two-character state code.
• You must ensure that the (DataBindings)-Text property of
the ComboBox = None – if this property is not cleared,
the ComboBox will not work correctly.
• ValidData function.
o Delete the code that validates the StateCodeTextBox.
o Add new code to validate the StateComboBox as shown here.
1. Select the Project menu, Add Windows Form option and add a new
form named VBUniversityParent.vb.
You can use this same approach to code the Student Grid, Student-
Enrollment Grid, and Student Details menu items. Note that the same
generic form name is used, thus making it easier to copy/past/modify the
code.
12. Add the code for these three sub procedures to the program.
This figure shows two forms open in windows arranged for display by
cascading. Note the Window menu displays a listing of each form
automatically due to setting the MdiWindowListItem property of the
menu strip control to the Window menu item.
Code File Close and Exit Menu Options
The code for the Close menu item under the File menu is shown here.
• The Me.ActiveMdiChild property is checked to determine if there
is an active child form with the If statement. This is done by
comparing the value of the property to the keyword Is Nothing.
• The Me.ActiveMdiChild.Close method closes the currently
selected (active) child form.
The code for the Exit menu item under the File menu is straight-forward
– all open child forms will automatically close.
13. Add the code for the Close and Exit ToolStripMenuItem click
event sub procedures to the program.
Parent Form
'Project: Ch10VBUniversity-AccessVersion
'D. Bock
'Today's Date
Option Strict On
#End Region
#End Region
#End Region
End Class
CourseGrid form
'Project: Ch10VBUniversity-AccessVersion
'D. Bock
'Today's Date
Option Strict On
End Class
Option Strict On
End Class
Option Strict On
End Class
Option Strict On
'Enable/disable ComboBox
LastNameComboBox.Enabled = ValueBoolean
End Sub
'Set focus
SSNMaskedTextBox.Focus()
End Sub
Try
Dim ResponseDialogResult As DialogResult = MessageBox.Show("Confirm to
delete the student record.", "Delete
Y/N?", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Butto
n2)
Catch ex As Exception
'Some other exception was triggered
MessageBox.Show("Unexpected error in delete operation:
" & ControlChars.NewLine & ex.Message, "Delete Operation
Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
End Class
END OF NOTES