未使用对象实例设置的对象变量

时间:2011-03-24 07:48:20

标签: .net vb.net visual-studio-2010

只是因为(在我的代码中)有时看起来sqlDataReader打开并告诉我“已经有一个开放的数据读取器”
我决定把这一行:If Not SqlReader.IsClosed Then SqlReader.Close()

Select Case PreviousRecord
    Case True
        SqlComm = New SqlCommand("Select * from " & tmpName & " where FuelOrderValid = '" & True & "' Order by FuelLoadDate", ReportsSQLConn)
    Case False
        SqlComm = New SqlCommand("Select * from " & tmpName & " where FuelOrderValid = '" & True & "' And FuelOrderID = '" & ordNum & "' Order by FuelLoadDate", ReportsSQLConn)
End Select      

If Not SqlReader.IsClosed Then SqlReader.Close()

If SqlComm.Connection.State = Data.ConnectionState.Open Then
    SqlReader = SqlComm.ExecuteReader(CommandBehavior.KeyInfo)
Else
    SqlComm.Connection.Open()
    SqlReader = SqlComm.ExecuteReader(CommandBehavior.KeyInfo)
End If

但是现在,当执行指令时 If Not SqlReader.IsClosed Then SqlReader.Close()
它给出了错误:
Object Variable Not Set To An Instance Of An Object
我真的不明白为什么这样做。
请有人帮助我吗?

1 个答案:

答案 0 :(得分:4)

在致电SqlReaderSqlReader.IsClosed之前,SqlReader.Close尚未初始化。你可以检查它的nothing是否像这样:

If SqlReader IsNot Nothing Then
    ' Do something with the SqlReader'
Else
    ' Create a new SqlReader'
End If