|
-
Mar 5th, 2008, 03:29 AM
#1
Thread Starter
New Member
[02/03]
Hi all,
I am new to the VB.net. I am trying to connect db with very simple code but giving following error:
An unhandled exception of type 'System.NullReferenceException' occurred in TestConn.exe
Additional information: Object reference not set to an instance of an object.
See the CODE below:
Imports System.Data
Imports System.Data.OleDb
Imports System.Data.SqlClient
Public Class Form1
Inherits System.Windows.Forms.Form
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim con As OleDb.OleDbConnection
con.ConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source = C:\Documents and Settings\img\My Documents\Visual Studio Projects\TestConn\AddressBook.mdb"
con.Open()
MsgBox("A Connection to the Database is now open")
con.Close()
MsgBox("The Connection to the Database is now Closed")
End Sub
End Class
Pls help me to solve the prob.
Thanks,
Gitesh
-
Mar 5th, 2008, 04:07 AM
#2
Fanatic Member
Re: [02/03]
Before you can use the 'con' variable, you must use the 'New' instruction for the compiler to allocate a valid reference to your variable.
your code should be like this
vb Code:
Imports System.Data Imports System.Data.OleDb Imports System.Data.SqlClient Public Class Form1 Inherits System.Windows.Forms.Form Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim con As New OleDb.OleDbConnection con.ConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source = C:\Documents and Settings\img\My Documents\Visual Studio Projects\TestConn\AddressBook.mdb" con.Open() MsgBox("A Connection to the Database is now open") con.Close() MsgBox("The Connection to the Database is now Closed") End Sub End Class
-
Mar 5th, 2008, 04:10 AM
#3
Fanatic Member
Re: [02/03]
Yes, to brief you need to change just one line of your code.
vb Code:
Dim con As New OleDb.OleDbConnection 'New keyword added
-
Mar 8th, 2008, 01:57 AM
#4
Thread Starter
New Member
Re: [02/03]
Thanks talkro...Problem Solved.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|