Results 1 to 4 of 4

Thread: [02/03]

  1. #1

    Thread Starter
    New Member
    Join Date
    Mar 2008
    Posts
    2

    [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

  2. #2
    Fanatic Member
    Join Date
    Feb 2007
    Location
    Eindhoven
    Posts
    828

    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:
    1. Imports System.Data
    2. Imports System.Data.OleDb
    3. Imports System.Data.SqlClient
    4.  
    5. Public Class Form1
    6.          Inherits System.Windows.Forms.Form
    7.    
    8.     Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    9.        Dim con As New OleDb.OleDbConnection
    10.        con.ConnectionString = "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source = C:\Documents and Settings\img\My Documents\Visual Studio Projects\TestConn\AddressBook.mdb"
    11.        con.Open()
    12.        MsgBox("A Connection to the Database is now open")
    13.        con.Close()
    14.        MsgBox("The Connection to the Database is now Closed")
    15.     End Sub
    16. End Class

  3. #3
    Fanatic Member pvbangera's Avatar
    Join Date
    Sep 2001
    Location
    Mumbai, India
    Posts
    961

    Re: [02/03]

    Yes, to brief you need to change just one line of your code.

    vb Code:
    1. Dim con As New OleDb.OleDbConnection 'New keyword added
    Microsoft Techie

  4. #4

    Thread Starter
    New Member
    Join Date
    Mar 2008
    Posts
    2

    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
  •  



Click Here to Expand Forum to Full Width