1/36
Database Programming with Visual Basic .Net and MS Access
2009.4.29
IKE Lab.Yunho Song
Database Management and Analysis
2/36
Database Programming with Visual Basic .Net and MS Access
Contents
1. Installation
2. VB .NET and Database
1. The Database Wizard (Visual Studio users)
2. Write your own VB .NET database code
3. Learn about DataSets and Data Adaptors
4. Display the Data in the DataSet
5. Navigate a Database with VB .NET
6. How to Move through the Database
7. Add, Update and Delete Records
8. Add a New Record using VB .NET
9. Delete a Record using VB .NET
10. A VB .NET Database Project
1. Installation
4/36
Installation
1. Installation
Database Programming with Visual Basic .Net and MS Access
5/36
1. Installation
Database Programming with Visual Basic .Net and MS Access Installation
6/36
1. Installation
Database Programming with Visual Basic .Net and MS Access Installation
7/36
1. Installation
Database Programming with Visual Basic .Net and MS Access
First run - choose the default environment settings
Installation
2. VB .NET and Database
9/36
VB .NET and Database
Let's make a start on our Database projectClick File > New Project from the menu barSelect Windows Application, and then give it the Name AddressBook. Click OKLocate the Solution Explorer on the right hand side
Database Programming with Visual Basic .Net and MS Access
2.1. Database Wizard
Select Data Sources
10/36
VB .NET and Database
The Wizard display all your tables, fields and objects
Database Programming with Visual Basic .Net and MS Access
2.1. Database Wizard
11/36
VB .NET and Database
The Data Sources area displays information about your database
Database Programming with Visual Basic .Net and MS Access
2.1. Database Wizard
Click the plus symbol next to tblContacts
12/36
VB .NET and Database
To add a Field to your Form
Database Programming with Visual Basic .Net and MS Access
2.1. Database Wizard
A textbox and a label will be added
13/36
VB .NET and Database
Run your program by hitting the F5 key
Database Programming with Visual Basic .Net and MS Access
2.1. Database Wizard
Drag and Drop more Fields to your form
14/36
The Connection ObjectWhat you need if you want to connect to a databaseOLE(Object Linking and Embedding)
•allow you to connect to data sources in general, and not just databases. You can
use it, for example, to connect to text files, SQL Server, email, and a whole lot more
Place a button on your form. Change the Name property to btnLoad
•Double click your button to open up the code window
• Add the following line:
Database Programming with Visual Basic .Net and MS Access
2.2. Write your own Database code
VB .NET and Database
Dim con As New OleDb.OleDbConnection
At the top of your code window, before Public Class Form 1, type the following:
Imports
System.Data
15/36
Database Programming with Visual Basic .Net and MS Access
2.2. Write your own Database code
VB .NET and Database
Coding window will look like this
Get a pop up box from where you can select OleDbConnectionUse to connect to an Access database
16/36
Database Programming with Visual Basic .Net and MS Access
2.2. Write your own Database code
VB .NET and Database
Setting a Connection StringThe technology is called the Provider; and you use "Data Source" to specify where
your database is
con.ConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source = C:\AddressBook.mdb"
The first part specifies which provider technology we want to use to do the connecting
(JET) The second part, typed after a semi-colon, points to where the database isIn the above code, the database is on the C drive, in the root folder. The name of the
Access file we want to connect to is called AddressBook.mdb
17/36
Database Programming with Visual Basic .Net and MS Access
2.2. Write your own Database code
VB .NET and Database
Opening the Connection Open method of the Connection Object:
Close method of the Connection Object:
con.Open( )MsgBox("A Connection to the Database is now open“)
con.Close()MsgBox("The Connection to the Database is now Closed“)
18/36
Database Programming with Visual Basic .Net and MS Access
2.2. Write your own Database code
VB .NET and Database
Coding window
Test out our
code
19/36
Database Programming with Visual Basic .Net and MS Access
2.3. Data Sets and Data Adapters
VB .NET and Database
Data SetsHidden from you, and just stored in memoryImagine a grid with rows and columns. Each imaginary row of the DataSet represents
a Row of information in your Access database. And each imaginary column represents a
Column of information in your Access database (called a Field in Access)
Data AdapterThe Connection Object and the DataSet can't see each otherThey need a go-between so that they can communicateThis go-between is called a Data AdapterThe Data Adapter contacts your Connection Object, and then executes a query that
you set up. The results of that query are then stored in the DataSet.
20/36
Database Programming with Visual Basic .Net and MS Access
2.3. Data Sets and Data Adapters
VB .NET and Database
Data Adapter and DataSet are objects
OleDb.OleDbDataAdapter
•Called da
•Hold a reference to the Data Adapter
da = New OleDb.OleDbDataAdapter(sql, con)
•creates a new Data Adapter object
•Need to put two things in the round brackets of the Object declaration
•SQL string (which we'll get to shortly), and connection object
•Connection Object is stored in the variable called con
Data Adaptor acting as a go-between for the Connection Object and the Data Set
Dim ds As New DataSetDim da As OleDb.OleDbDataAdapterda = New OleDb.OleDbDataAdapter(sql, con)
21/36
Database Programming with Visual Basic .Net and MS Access
2.3. Data Sets and Data Adapters
VB .NET and Database
Structured Query Language(SQL) A way to query and write to databases
•Hold a reference to the Data Adapter
To select just the first name and surname columns from our database
To SELECT all (*) the records from the table called tblContacts
Select * from Table_Name
SELECT tblContacts.FirstName, tblContacts.Surname FROM tblContacts
sql = "SELECT * FROM tblContacts”
22/36
Database Programming with Visual Basic .Net and MS Access
2.3. Data Sets and Data Adapters
VB .NET and Database
Structured Query Language(SQL)
Dim ds As New DataSetDim da As OleDb.OleDbDataAdapterDim sql As String
sql = "SELECT * FROM tblContacts"da = New OleDb.OleDbDataAdapter(sql, con)
23/36
Database Programming with Visual Basic .Net and MS Access
2.3. Data Sets and Data Adapters
VB .NET and Database
Filling the DataSetData Adapter can Fill a DataSet with records from a Table
The DataSet (ds) will now be filled with the records we selected from the table called
tblContactOne slight problem - nobody can see the data yet! We'll tackle that in the next part
da = New OleDb.OleDbDataAdapter(sql, con)da.Fill(ds, "AddressBook“)
24/36
Database Programming with Visual Basic .Net and MS Access
2.4. Displaying the Data in the DataSet
VB .NET and Database
To display the records on a FormAdd two textboxes to your formChange the Name properties of your textboxes to txtFirstName and txtSurnameGo back to your code windowAdd the following two lines:
txtFirstName.Text = ds.Tables("AddressBook").Rows(0).Item(1)txtSurname.Text = ds.Tables("AddressBook").Rows(0).Item(2)
25/36
Database Programming with Visual Basic .Net and MS Access
2.5. Navigate a Database
VB .NET and Database
To see a more practical exampleAdd two Textboxes. Change the Name properties to txtFirstName and txtSurnameAdd four Buttons. Change the Name and Text properties to these:
Button Name Button TextbtnNext
btnPreviousbtnFirstbtnLast
Next RecordPrevious RecordFirst RecordLast Record
26/36
Database Programming with Visual Basic .Net and MS Access
2.5. Navigate a Database
VB .NET and Database
To see a more practical exampleAdd the following code to the Form1 Declarations area:
When the Form Loads, we can connect to our database, use the data Adaptor to grab
some records from the database and then put these records into the DataSet
•So in the Form1 Load Event, add the following code:
27/36
Database Programming with Visual Basic .Net and MS Access
2.5. Navigate a Database
VB .NET and Database
To see a more practical exampleYou've met all the code before, except for these two lines:
In the MaxRows variable, we can store how many rows are in the DataSetGet how many rows are in DataSet with Rows.Count:
To navigate through the recordsUse inc variable. We'll either add 1 to it, or take 1 awayUse the variable for the Rows in the DataSetIt's better to do this in a Subroutine of ownSo add this Sub to code:
MaxRows = ds.Tables("AddressBook").Rows.Countinc = -1
Private Sub NavigateRecords()txtFirstName.Text = ds.Tables("AddressBook").Rows(inc).Item(1)txtSurname.Text = ds.Tables("AddressBook").Rows(inc).Item(2)End Sub
28/36
Database Programming with Visual Basic .Net and MS Access
2.5. Navigate a Database
VB .NET and Database
The important part is Rows(inc). This moves us through the Rows in the
DataSet. Then placing the values into the two Textboxes
29/36
Database Programming with Visual Basic .Net and MS Access VB .NET and Database
How to Move Forward One Record at a TimeDouble click your Next Record button to access the code
2.6. How to Move through the Database
Move Back One Record at a Timeto add to your btnPrevious:
If inc > 0 Theninc = inc - 1NavigateRecords()ElseIf inc = -1 ThenMsgBox("No Records Yet")ElseIf inc = 0 ThenMsgBox("First Record")End If
If inc <> MaxRows - 1 Theninc = inc + 1NavigateRecords()ElseMsgBox("No More Rows")End If
30/36
Database Programming with Visual Basic .Net and MS Access VB .NET and Database
Moving to the Last Record in the DataSetto add to your btnLast:
2.6. How to Move through the Database
If inc <> MaxRows - 1 Theninc = MaxRows - 1NavigateRecords()End If
Moving to the First Record in the DataSetto add to your btnFirst:
If inc <> 0 Theninc = 0NavigateRecords()End If
31/36
Database Programming with Visual Basic .Net and MS Access VB .NET and Database
DataSet is disconnected from the databaseNot adding the record to the database: adding it to the DataSet
How to add, delete, update new recordsAdd five more buttons to your form
2.7. Add, Update and Delete Records
Change the Name properties
btnAddNewbtnCommitbtnUpdatebtnDeletebtnClear
32/36
Database Programming with Visual Basic .Net and MS Access VB .NET and Database
Updating a RecordThe changes will just get made to the DataSetAdd the following code to btnUpdate:
2.7. Add, Update and Delete Records
ds.Tables("AddressBook").Rows(inc).Item(1) = txtFirstName.Textds.Tables("AddressBook").Rows(inc).Item(2) = txtSurname.Text
MsgBox("Data updated“)
"Changes are made to the DataSet, and NOT to the Database“To update the database, Add following code
Dim cb As New OleDb.OleDbCommandBuilder(da)
ds.Tables("AddressBook").Rows(inc).Item(1) = txtFirstName.Textds.Tables("AddressBook").Rows(inc).Item(2) = txtSurname.Text
da.Update(ds, "AddressBook")
MsgBox("Data updated“)
33/36
Database Programming with Visual Basic .Net and MS Access VB .NET and Database
Add a New RecordAdd New Record button:
2.8. How to Add a New Record
btnCommit.Enabled = TruebtnAddNew.Enabled = FalsebtnUpdate.Enabled = FalsebtnDelete.Enabled = False
txtFirstName.Clear()txtSurname.Clear()
The Clear/Cancel button can be used to switch it back on againAdd this code to btnClear:btnCommit.Enabled = FalsebtnAddNew.Enabled = TruebtnUpdate.Enabled = TruebtnDelete.Enabled = True
inc = 0NavigateRecords()
34/36
Database Programming with Visual Basic .Net and MS Access VB .NET and Database
To add a new record to the databaseAdd this code to btnCommit
2.8. How to Add a New Record
If inc <> -1 ThenDim cb As New OleDb.OleDbCommandBuilder(da)Dim dsNewRow As DataRow
dsNewRow = ds.Tables("AddressBook").NewRow()
dsNewRow.Item("FirstName") = txtFirstName.TextdsNewRow.Item("Surname") = txtSurname.Text
ds.Tables("AddressBook").Rows.Add(dsNewRow)
da.Update(ds, "AddressBook“)MsgBox("New Record added to the Database“)btnCommit.Enabled = FalsebtnAddNew.Enabled = TruebtnUpdate.Enabled = TruebtnDelete.Enabled = True
End If
35/36
Database Programming with Visual Basic .Net and MS Access VB .NET and Database
Deleting Records from a DatabaseAdd this code to btnDelete
2.8. Delete a Record from a Database
Dim cb As New OleDb.OleDbCommandBuilder(da)
ds.Tables("AddressBook").Rows(inc).Delete()MaxRows = MaxRows - 1
inc = 0NavigateRecords()da.Update(ds, "AddressBook“)
To display a message box asking users if they really want to delete this recordIf MessageBox.Show("Do you really want to Delete this Record?", _"Delete", MessageBoxButtons.YesNo, _MessageBoxIcon.Warning) = DialogResult.No Then
MsgBox("Operation Cancelled")Exit Sub
End If
36/36
Thank You!!