开发者

Error in Code - dbCommand.ExecuteReader()

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 开发者_如何学Chere 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


Part of the programma:

Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        'MajDgv()
        Module1.connect()
        Me.fillcombo()
End Sub
Sub fillcombo()

        strsql = "select from Liste des responsables"
        Dim acscmd As New OleDb.OleDbCommand
        Dim acsdr As OleDbDataReader
        acscmd.CommandText = strsql
        acsdr = acscmd.ExecuteReader()""THE PROBLEM IS HERRE he sayed that ExecuteReader: Connection property has not been initialized."""""""
        While (acsdr.Read())
            ComboBox1.Items.Add(acsdr("Nom"))

        End While
        acscmd.Dispose()
        acsdr.Close()

    End Sub
End Class

I create a Module:

Imports System.Data.OleDb
Module Module1
    Public acsconn As New OleDb.OleDbConnection
    Public acsdr As OleDbDataReader
    Public strsql As String
    Sub connect()
        acsconn.ConnectionString = "Provider=Microsoft.ace.oledb.12.0;data source=|datadirectory|\Base1.accdb;"
        acsconn.Open()
    End Sub
End Module
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜