Public Class txtSurname

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim cn As OleDb.OleDbConnection
    'Dim con As OleDb.OleDbConnection
    Dim dbProvider As String
    Dim dbSource As String
    Dim DS As New DataSet
    Dim DA As OleDb.OleDbDataAdapter
    Dim sql As String

    dbProvider = "PROVIDER=Microsoft.Jet.OLEDB.4.0;"
    dbSource = "Data source =C:\test2\addressBook.mdb"
    cn.ConnectionString = dbProvider & dbSource
    cn.Open()
    sql = " select * from tblcontacts"
    DA = New OleDb.OleDbDataAdapter(sql, cn)

    MsgBox("Database is now open")
    cn.Close()
    MsgBox("Database is now closed")

    DA.Fill(DS, "AddressBook")
    DA.Fill(DS, "Bacon Sandwich")
    DA = New OleDb.OleDbDataAdapter(sql, cn)
    DA.Fill(DS, "AdressBook")

    txtfirstName.Text = DS.Tables("AdressBook").Rows(0).Item(1)
    Me.txtsname.Text = DS.Tables("AdressBook").Rows(0).Item(2)

End Sub

End Class

Object reference not set to an instance of an object.
Public Class txtSurname

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim cn As OleDb.OleDbConnection
        'Dim con As OleDb.OleDbConnection
        Dim dbProvider As String
        Dim dbSource As String
        Dim DS As New DataSet
        Dim DA As OleDb.OleDbDataAdapter
        Dim sql As String

        dbProvider = "PROVIDER=Microsoft.Jet.OLEDB.4.0;"
        dbSource = "Data source =C:\test2\addressBook.mdb"
        cn.ConnectionString = dbProvider & dbSource
        cn.Open()
        sql = " select * from tblcontacts"
        DA = New OleDb.OleDbDataAdapter(sql, cn)

        MsgBox("Database is now open")
        cn.Close()
        MsgBox("Database is now closed")

        DA.Fill(DS, "AddressBook")
        DA.Fill(DS, "Bacon Sandwich")
        DA = New OleDb.OleDbDataAdapter(sql, cn)
        DA.Fill(DS, "AdressBook")

        txtfirstName.Text = DS.Tables("AdressBook").Rows(0).Item(1)
        Me.txtsname.Text = DS.Tables("AdressBook").Rows(0).Item(2)

    End Sub

Recommended Answers

All 3 Replies

Please can anyone give me solution for this error "Object reference not set to an instance of an object.

On what line do you get this error?

You haven't created the objects. The statement

Dim cn As OleDb.OleDbConnection

says "allocate a variable named cn that can be used to access an OleDbConnection object. That statement doesn't actually create the object (it isn't pointing at anything). You need to use

Dim cn As New OleDb.OleDbConnection

This creates the object AND stores the address of it in cn. You have to do this for every object that you want to use.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.