Hi guys,

Am developing a clinical management system in VB.net and using Microsoft Access for the database. Everything else is working very well. But the login code is not working. It's throing an error message "Object reference not set to an instance of an object" on line 12. Below is the code for the log in button.

Imports System.Data
Imports System.Data.OleDb

Public Class frmLogin
    Dim myConnToAccess As OleDb.OleDbConnection

    Private Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click


            myConnToAccess.ConnectionString = ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Application.StartupPath & "/Clinic.accdb")

            Dim query As String

            query = "SELECT UserID,UserPass FROM tblUsers WHERE (UserID = '" & txtUsername.Text & "' ) AND (UserPass = '" & txtPassword.Text & "')"

            Dim cmd As New OleDbCommand(query, myConnToAccess)

                Dim read As OleDbDataReader = cmd.ExecuteReader()

                If read.HasRows Then


                    If Me.txtUsername.Text.ToLower() = read.Item("UserID").ToString And Me.txtPassword.Text.ToLower = read.Item("UserPass").ToString Then


                        txtUsername.Text = ""

                    End If

                    MsgBox("Sorry, Acces Denied, Invalid ID or Password", MsgBoxStyle.OkOnly, "Caution")

                    txtPassword.Text = ""

                End If

            End Try

        Catch ex As Exception

        End Try
    End Sub
End Class

The message "Object not set to instance of Object" means that you are trying to use an object which has not been initialized. That is, you either set it to null, or you never set it to anything at all. The runtime throwing a NullReferenceException always means the same thing: you are trying to use a reference. The reference is not initialized (or it was initialized, but is no longer initialized).

In your case you have not set an instance of "myConnToAccess".

myConnToAccess = new OleDb.OleDbConnection

You can now use this instance to connect to your database.
This should do the trick.

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.