I am trying to launch a command from this class:
Imports System.Data.OleDb
Imports System.IO
Public Class GestionSql
Private sReturn As String = ""
Private sConection As String = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" +Directory.GetCurrentDirectory() + "\TPV.mdb;"
Private oConection As OleDb Connection
Public oCommand As New OleDbCommand
Public Function Launch(ByVal value As String) As String
Try
oConection.Open()
oConection = New OleDbConnection(sConection)
oCommand.CommandText = Value
sReturn = oCommand.ExecuteNonQuery()
oConection.Close()
MessageBox.Show("La contraseña es: " + sReturn.ToString)
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
Return sReturn
End Function
End Class
In this class:
Public Class IDVendedor
Private GestionSql As New GestionSql
Private sCmd As String
Private sPass As String
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'Montamos y lanzamos el comando
sCmd = "SELECT Password FROM Vendedores WHERE Id=" + id.Text
sPass = GestionSql.Launch(sCmd)
End Sub
End Class
I get the error:
Object reference not set to an instance of an object. It tells me that the error is in ExecuteNonQuery in the sCmd parameter.
The error
Referencia a objeto no establecida como instancia de un objeto
will accompany you for many years in the world of programming, but soon you will get used to knowing immediately where the error is :)What does that message mean?
You are reading a property or executing a function from an object variable ("object reference") that has not been initialized ("not set to an instance of an object"). That is, you declared a variable and used it without first assigning it a value.
The error appears on line 15 of your capture, because you have reversed the initialization of the variable
oConexion
(line 16) and the first use (line 15):To solve you just have to initialize the variable
oConexion
before opening the connection:In the code I see you are trying to use oConnection before initializing it, in theory your problem could be solved by changing this:
For this:
Explanation:
oConection
it is the samenull
as beingnull
or not being initialized, you cannot access its methods or attributes, so before calling.open()
you need to assign a value to it when using=new
create a new instance of this object and this is how you avoid the Object not error initialized .What I see is that you need to initialize oConnection, but you would have to validate it, check the image to see if it can help you in any way.
In the end I solved it in the following way: