Can anyone tell me How do I solve this error.
Error: NullReferenceException was Unhandled – “Object reference not set to an instance of an object.”
Line: Dim reader As OleDbDataReader = dbCommand.ExecuteReader()
Database: MS Access
IDE: VB 2010 Express
Imports System.Data.OleDb
Imports System.Data.SqlClient
Imports System
Public Class Form1
Dim dbConnection As OleDbConnection
Dim dbCommand As OleDbCommand
Dim strInsert As String
Dim dbDataAdapter As OleDbDataAdapter
Dim ConnectString As String = "Provider = Microsoft.Jet.OLEDB.4.0;" & "Data Source =atg.mdb"
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
dbConnection = New OleDbConnection(ConnectString) 'here I use the new keyword to initialize connection
dbConnection.Open()
Dim command As New OleDbCommand("SELECT XX FROM ABC", dbConnection) ' initialize command and pass query and open connection to its constructor
Dim reader As OleDbDataReader = dbCommand.ExecuteReader() 'ERROR IS HERE
Do While (reader.Read()) ' loop here until reader finish reading and add every row to the list box
ListBox1.BeginUpdate()
ListBox1.Items.Add(reader.Item("ABC"))
ListBox1.EndUpdate()
Loop
reader.Close()
dbConnection.Close()
End Sub
End Class
Where you find dbCommand in dbCommand.ExecuteReader() statement.Use command.ExecuteReader() instead .
You didn’t initiate your dbCommand.You just Decalared it.What you did is creating another variable called command and initiated it.So try with this