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

        Try

            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)

            Try
                myConnToAccess.Open()
                Dim read As OleDbDataReader = cmd.ExecuteReader()

                If read.HasRows Then

                    read.Read()

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

                        frmMenu.Show()

                        txtUsername.Text = ""

                    End If

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

                    txtPassword.Text = ""

                End If
                read.Close()

            Finally
                myConnToAccess.Close()
            End Try

        Catch ex As Exception
            MsgBox(ex.Message)

        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.