Professional Documents
Culture Documents
PROJECT
PROJECT
Import Imports System.Data.OleDb library. This library package is for ms access database.
In your module connection, initialize the following variables.
1. Module modConnection
2.
3. Public cn As New OleDb.OleDbConnection
4. Public cm As New OleDb.OleDbCommand
5. Public dr As OleDbDataReader
Now, create a method named connection to have the connection string.
This will locate the StudentDB access database created earlier.
1. Public Sub connection()
2. cn = New OleDb.OleDbConnection
3. With cn
4. 'Provider must be Microsoft.Jet.OLEDB.4.0, find the access file, and test the connection
5. .ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Application.StartupPath
& "\sample.mdb"
6. .Open()
7. End With
8. End Sub
5. Back to our form, put this code for the form_load. We will call the connetion() method that we have created in our module. Because
we all know that module is access throughout the entire program.
1. Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles MyBase.Load
2. Call connection()
3. End Sub
6. For the btnAdd as adding and saving records to database button, put this code below.
We will first create a try and catch method to have the exception handling. Here, we will use the OleDbCommand with the method of
connection, CommandType.Text, and CommandText, with the OleDbDataReader to execute the CommandText. Note: The sql syntax
"INSERT INTO tblStudent (Snum,Sname,Scourse,Ssection) VALUES (@Snum,@Sname,@Scourse,@Ssection)" is for adding and
saving of records to the database. Snum,Sname,Scourse, and Ssection are our entities and @Snum,@Sname,@Scourse,@Ssection
are our parameters.
1. Try
2.
3. cm = New OleDb.OleDbCommand
4. With cm
5. .Connection = cn
6. .CommandType = CommandType.Text
7. .CommandText = "INSERT INTO tblStudent (Snum,Sname,Scourse,Ssection) VALUES
(@Snum,@Sname,@Scourse,@Ssection)"
To run the command of our parameters put this code below.
1. cm.Parameters("@Snum").Value = Me.txtSearch.Text
2. cm.Parameters("@Sname").Value = Me.txtName.Text
3. cm.Parameters("@Scourse").Value = Me.txtCourse.Text
4. cm.Parameters("@Ssection").Value = Me.txtSection.Text
Execute the non query and have a message of "Record Saved" after execution.
Clear all the textboxes after saving the records. And don't forget the Exit Sub command at the end of your Try method.
This will terminate the sub process of trying to add again another record.
1. Me.txtCourse.Text = ""
2. Me.txtName.Text = ""
3. Me.txtSearch.Text = ""
4. Me.txtSection.Text = ""
5. Exit Sub