In todays tutorial we will be discussing the basics of interacting with Access (or any other than require the OleDb Objects) in VB.Net. These code ideas will be from a Windows Application, but with some (if any) modifications they can be used in a VB.Net Web Application. All the function in this tutorial are
Public Shared because I always put them in their own class file, this way I can reference the class file itself, and not have to create a new instance of it.
If your project don't already have one add an app.config file, in it you will be storing your connection string information for later retrieval. Your connection should look like this:
CODE
< connectionStrings>
<add name="YourConnectionName"
connectionString="Persist Security Info=False;
Data Source=YourDatabase;
Initial Catalog=YourTable;
Integrated Security=SSPI;
Trusted_Connection=TRUE;
Application Name=SampleVBNetApplication"
providerName="System.Data.OleDb" />
</connectionStrings>
We will be referencing this connectionString in our next code snippet. Add a new Class and name it DataAccess, then at the top of you class add this Imports statement
CODE
Imports System.Data.OleDb
This is needed for working with OleDb Objects in the .Net Framework. The first code you will add to this class is a method to retrieve the connectionString from the app.config file. The method is GetConnectionString, and it includes this code:
CODE
''' <summary>
''' Function to retrieve the connection from the app.config
''' </summary>
''' <param name="conName">Name of the connectionString to retrieve</param>
''' <returns></returns>
''' <remarks></remarks>
Public Shared Function GetConnectionString(ByVal conName As String) As String
'variable to hold our connection string for returning it
Dim strReturn As New String("")
'check to see if the user provided a connection string name
'this is for if your application has more than one connection string
If Not String.IsNullOrEmpty(conName) Then
'a connection string name was provided
'get the connection string by the name provided
strReturn = ConfigurationManager.ConnectionStrings(conName).ConnectionString
Else
'no connection string name was provided
'get the default connection string
strReturn = ConfigurationManager.ConnectionStrings("YourConnectionName").ConnectionString
End If
'return the connection string to the calling method
Return strReturn
End Function
Now, this method does several things:
- Checks to see if a connection name was provided
- If one was provided get the connection information for that name
- If one wasnt provided it returns the default connection information (as set by you the developer)
- Return the connection information to the calling method
Most people are retrieving data for populating a control, whether it be a DataGrid, A DataRepeater, etc. The easiest way I've found to populate these controls is with a BindingSource. According to the MSDN, this is the definition of a Binding Source:
QUOTE
The BindingSource component serves many purposes. First, it simplifies binding controls on a form to data by providing currency management, change notification, and other services between Windows Forms controls and data sources. This is accomplished by attaching the BindingSource component to your data source using the DataSource property.
More:
BindingSource So to retrieve a BindingSource for a Data control I use a function that I pass a OleDbCommand Object to it, it then executes that OleDbCommand Object and puts the returned data into a BindingSource Object for me, making it easy to bind to a control. This function looks like this:
CODE
''' <summary>
''' Returns a BindingSource, which is used with, for example, a DataGridView control
''' </summary>
''' <param name="cmd">"pre-Loaded" command, ready to be executed</param>
''' <returns>BindingSource</returns>
''' <remarks>Use this function to ease populating controls that use a BindingSource</remarks>
Public Shared Function GetBindingSource(ByVal cmd As OleDbCommand) As BindingSource
'declare our binding source
Dim oBindingSource As New BindingSource()
' Create a new data adapter based on the specified query.
Dim daGet As New OleDbDataAdapter(cmd)
' Populate a new data table and bind it to the BindingSource.
Dim dtGet As New DataTable()
'set the timeout of the OleDbCommandObject
cmd.CommandTimeout = 240
dtGet.Locale = System.Globalization.CultureInfo.InvariantCulture
Try
'fill the DataTable with the OleDbDataAdapter
daGet.Fill(dtGet)
Catch ex As Exception
'check for errors
MsgBox(ex.Message, "Error in GetBindingSource")
Return Nothing
End Try
'set the DataSource for the BindingSource to the DataTable
oBindingSource.DataSource = dtGet
'return the BindingSource to the calling method or control
Return oBindingSource
End Function
Heres how the GetBindingSource method works:
- Pass the method your OleDbCommand Object from your method (this is already created and "pre-loaded" when you pass it)
- Create a OleDbDataAdapter Object based on this OleDbCommand Object
- Create and fill a DataTable Object with the OleDbDataAdapter (this executes your OleDbCommand Object)
- Set the DataSource property of your BindingSource Object to you now filled DataTable Object
- Return the BindingSource Object to the calling method for binding
The last thing to add to your DataAccess class is a way to open and close the OleDbConnection based on its current state. I created a method called HandleConnection, and you pass a OleDbConnection then the method checks the status of the connection and acts accordingly. This procedure looks like this:
CODE
''' <summary>
''' Method for handling the ConnectionState of
''' the connection object passed to it
''' </summary>
''' <param name="conn">The OleDbConnection Object</param>
''' <remarks></remarks>
Public Shared Sub HandleConnection(ByVal conn As OleDbConnection)
With conn
'do a switch on the state of the connection
Select Case .State
Case ConnectionState.Open
'the connection is open
'close then re-open
.Close()
.Open()
Exit Select
Case ConnectionState.Closed
'connection is open
'open the connection
.Open()
Exit Select
Case Else
.Close()
.Open()
Exit Select
End Select
End With
End Sub
This covers 3 important methods, and also saves a lot of coding down the road. For the next part you can either keep them in the DataAccess Class (my choice) or put it right in your form .vb file.
First I will show you how to insert a new record into a table. For this I create a Public Shared Function that returns a boolean value (True for succeeded, False for failed). Always use a
Try...Catch block to help catch and deal with any errors that may occur, especially when working with a database.
In this function we pass the values we want inserted into our table (I only have 3 in this example, there can be as many as you need though). We then create the objects we need for this, OleDbCommand, OleDbConnection and a String variable query. We set the query variable to the query we want to execute (or the inline SQL if you go that route), then we set the properties of our OleDbCommand Object.
Once this is complete we open the connection to the database, we use
ExecuteNonQuery to insert the values.
ExecuteNonQuery is what you use when you're not returning a value from the database. Once we complete the insert we check the status and act accordingly, then we close the connection. Here is more on the objects we created
- A OleDbCommand Object -> This will perform your query execution
- A OleDbConnection -> This will be used to communicate with the database
- A String (query) -> This will hold the name of your query
Now to the function:
CODE
Public Shared Function InsertNewRecord(ByVal item1 As String, ByVal item2 As String, ByVal item3 As String) As Boolean
'Create the objects we need to insert a new record
Dim cnInsert As New OleDbConnection(GetConnectionString("YourConnName"))
Dim cmdInsert As New OleDbCommand
Dim query As String = "INSERT INTO YourTable(column1,column2,column3) VALUES(@item1,@item2,@item3)"
Dim iSqlStatus As Integer
'Clear any parameters
cmdInsert.Parameters.Clear()
Try
'Set the OleDbCommand Object Properties
With cmdInsert
'Tell it what to execute
.CommandText = query
'Tell it its a text query
.CommandType = CommandType.Text
'Now add the parameters to our query
'NOTE: Replace @value1.... with your parameter names in your query
'and add all your parameters in this fashion
.Parameters.AddWithValue("@value1", item1)
.Parameters.AddWithValue("@value2", item2)
.Parameters.AddWithValue("@value3", item3)
'Set the connection of the object
.Connection = cnInsert
End With
'Now take care of the connection
HandleConnection(cnInsert)
'Set the iSqlStatus to the ExecuteNonQuery
'status of the insert (0 = failed, 1 = success)
iSqlStatus = cmdInsert.ExecuteNonQuery
'Now check the status
If Not iSqlStatus = 0 Then
'DO your failed messaging here
Return False
Else
'Do your success work here
Return True
End If
Catch ex As Exception
MsgBox(ex.Message, "Error")
Finally
'Now close the connection
HandleConnection(cnInsert)
End Try
End Function
Next we will look at updating a record in the database. In this function we pass the values of the record we want to update, along with the id of the record to update (I only have 2 values in this example but you can have more in yours). We then create the objects we need for this, OleDbCommand, OleDbConnection and a String variable query. We set the query variable to the query we want to execute, then we set the properties of our OleDbCommand Object.
Once this is complete we open the connection to the database, we use
ExecuteNonQuery to insert the values.
ExecuteNonQuery is what you use when you're not returning a value from the database. Once we complete the insert we check the status and act accordingly, then we close the connection. Here is the function:
CODE
Public Shared Function UpdateRecord(ByVal item1 As String, ByVal item2 As String, ByVal id As Integer) As Boolean
'Create the objects we need to insert a new record
Dim cnUpdate As New OleDbConnection(GetConnectionString("YourConnName"))
Dim cmdUpdate As New OleDbCommand
Dim query As String = "UPDATE YourTable SET column1 = @item1,column2 = @item2 WHERE YourId = @id"
Dim iSqlStatus As Integer
'Clear any parameters
cmdUpdate.Parameters.Clear()
Try
'Set the OleDbCommand Object Properties
With cmdUpdate
'Tell it what to execute
.CommandText = query
'Tell it its a text query
.CommandType = CommandType.Text
'Now add the parameters to our query
'NOTE: Replace @value1.... with your parameter names in your query
'and add all your parameters in this fashion
.Parameters.AddWithValue("@value1", item1)
.Parameters.AddWithValue("@value2", item2)
.Parameters.AddWithValue("@YourID", id)
'Set the connection of the object
.Connection = cnUpdate
End With
'Now take care of the connection
HandleConnection(cnUpdate)
'Set the iSqlStatus to the ExecuteNonQuery
'status of the insert (0 = success, 1 = failed)
iSqlStatus = cmdUpdate.ExecuteNonQuery
'Now check the status
If Not iSqlStatus = 0 Then
'DO your failed messaging here
Return False
Else
'Do your success work here
Return True
End If
Catch ex As Exception
MsgBox(ex.Message, "Error")
Finally
'Now close the connection
HandleConnection(cnUpdate)
End Try
End Function
Next we will look at deleting a record from a table. In this function we pass the id of the record we want to delete. We then create the objects we need for this, OleDbCommand, OleDbConnection and a String variable query. We set the query variable to the query we want to execute, then we set the properties of our OleDbCommand Object.
Once this is complete we open the connection to the database, we use
ExecuteNonQuery to insert the values.
ExecuteNonQuery is what you use when you're not returning a value from the database. Once we complete the insert we check the status and act accordingly, then we close the connection. Here is the function:
CODE
Public Shared Function DeleteRecord(ByVal id As Integer) As Boolean
'Create the objects we need to insert a new record
Dim cnDelete As New OleDbConnection(GetConnectionString("YourConnName"))
Dim cmdDelete As New OleDbCommand
Dim query As String = "DELETE FROM YourTable WHERE YourID = @id"
Dim iSqlStatus As Integer
'Clear any parameters
cmdDelete.Parameters.Clear()
Try
'Set the OleDbCommand Object Properties
With cmdDelete
'Tell it what to execute
.CommandText = query
'Tell it its a text query
.CommandType = CommandType.Text
'Now add the parameters to our query
'NOTE: Replace @value1.... with your parameter names in your query
'and add all your parameters in this fashion
.Parameters.AddWithValue("@YourID", id)
'Set the connection of the object
.Connection = cnDelete
End With
'Now take care of the connection
HandleConnection(cnDelete)
'Set the iSqlStatus to the ExecuteNonQuery
'status of the insert (0 = success, 1 = failed)
iSqlStatus = cmdDelete.ExecuteNonQuery
'Now check the status
If Not iSqlStatus = 0 Then
'DO your failed messaging here
Return False
Else
'Do your success work here
Return True
End If
Catch ex As Exception
MsgBox(ex.Message, "Error")
Return False
Finally
'Now close the connection
HandleConnection(cnDelete)
End Try
End Function
So far we have covered:
- Retrieving the connectionString from the app.config
- Retrieving a BindingSource for binding our data to a control
- A method to open and close our connection
- Inserting a new record into the database
- Updating a record in the database
- Deleting a record from a database
Next we will look at a basic retrieval of data from the database. This method will return a populated BindingSource so you can bind it to your data control and display your data. A SQL no parameters is the simplest database query, but lets say you want to filter your data by only returning certain data that falls into a certain category, you would then need parameters in your query. First lets take a look at returning all the data in the table, this function looks like this:
CODE
Public Shared Function GetRecords() As BindingSource
'The value that will be passed to the Command Object (this is a query)
Dim query As String = "SELECT * FROM YourTableName"
Dim cnGetRecords As New OleDbConnection(GetConnectionString("YourConnectionName"))
'OleDbConnection Object to use
Dim cmdGetRecords As New OleDbCommand()
'OleDbCommand Object to use
Dim daGetRecords As New OleDbDataAdapter()
Dim dsGetRecords As New DataSet()
'Clear any parameters
cmdGetRecords.Parameters.Clear()
Try
With cmdGetRecords
'set the OleDbCommand Object Parameters
.CommandText = query
'tell it what to execute
.CommandType = CommandType.Text
'Set the Connection for the Command Object
.Connection = cnGetRecords
End With
'set the state of the OleDbConnection Object
HandleConnection(cnGetRecords)
'create BindingSource to return for our DataGrid Control
Dim oBindingSource As BindingSource = GetBindingSource(cmdGetRecords)
'now check to make sure a BindingSource was returned
If Not oBindingSource Is Nothing Then
'return the binding source to the calling method
Return oBindingSource
Else
'no binding source was returned
'let the user know the error
Throw New Exception("There was no BindingSource returned")
Return Nothing
End If
Catch ex As Exception
MsgBox(ex.Message, "Error Retrieving Data")
Return Nothing
Finally
HandleConnection(cnGetRecords)
End Try
End Function
Next we will look at retrieval of data based on a criteria, a filter if you will. This method will return a populated BindingSource so you can bind it to your data control and display your data. A query with no parameters is the simplest database query, but lets say you want to filter your data by only returning certain data that falls into a certain category, you would then need parameters in your query. This function looks like this:
CODE
Public Shared Function GetRecordsByID(ByVal value As Integer) As BindingSource
'The value that will be passed to the Command Object (this is a query)
Dim query As String = "SELECT value1,value2,value3 FROM YourTable WHERE YourValue = @value"
Dim cnGetRecords As New OleDbConnection(GetConnectionString("YourConnectionName"))
'OleDbConnection Object to use
Dim cmdGetRecords As New OleDbCommand()
'OleDbCommand Object to use
Dim daGetRecords As New OleDbDataAdapter()
Dim dsGetRecords As New DataSet()
'Clear any parameters
cmdGetRecords.Parameters.Clear()
Try
With cmdGetRecords
'set the OleDbCommand Object Parameters
.CommandText = query
'tell it what to execute
.CommandType = CommandType.Text
'tell it its executing a text query
'heres the difference from the last method
'here we are adding a parameter to send to our query
'you use the AddWithValue, then the name of the parameter in your query
'then the variable that holds that value
.Parameters.AddWithValue("@id", value)
'Set the Connection for the Command Object
.Connection = cnGetRecords
End With
'set the state of the OleDbConnection Object
HandleConnection(cnGetRecords)
'create BindingSource to return for our DataGrid Control
Dim oBindingSource As BindingSource = GetBindingSource(cmdGetRecords)
'now check to make sure a BindingSource was returned
If Not oBindingSource Is Nothing Then
'return the binding source to the calling method
Return oBindingSource
Else
'no binding source was returned
'let the user know the error
Throw New Exception("There was no BindingSource returned")
Return Nothing
End If
Catch ex As Exception
MsgBox(ex.Message, "Error Retrieving Data")
Return Nothing
Finally
'Close the connection
HandleConnection(cnGetRecords)
End Try
End Function
There is essentially one difference in this method and the previous one, its the line
cmdGetRecords.Parameters.AddWithValue("@id", value). The AddWithValue accepts 2 parameters:
- The parameter name in your query (for this example the name is @year)
- The variable that is holding that value (in this case we pass it with the signature of the method -> value)
Now to use these methods in your form for binding a DataGridView to the data use this
CODE
'for binding to returning all the records
DataGridView1.DataSource = DirectCast(GetAllRecords(), BindingSource)
'for binding to to returning certain records
DataGridView1.DataSource = DirectCast(GetRecordsByID(DirectCast(TextBox1.Text, Integer)), BindingSource)
Her are the objects we used during this tutorial
If you have any questions please post them here so I can asnwer the question for you and anyone else who might have the same questions. Thanks for reading

Happy Coding!