Saturday, March 24, 2012

Object reference not set to an instance of an object

Would this be the wrong forum to ask about this error message?Nope, right forum..

You get this error when you reference an object that hasnt been created yet. Make sure your object is created before you use a property/method of it. You can also post the offending code so we can have a look to see where the problem is
Thank you. I get this error a lot when I'm coding and I never seem to understand it. I have a login page, I even used the same code from another project that works. Here is the code for the button to log in:


Private Sub btnGo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGo.Click
Dim SecurityLevel As String = mDbProcedures.Login(txtUserName.Text, txtPasscode.Text)
Session.Clear()
Session.Item("UserName") = txtUserName.Text
Session.Item("SecurityLevel") = SecurityLevel
Select Case SecurityLevel
Case "A"
Response.Redirect("Admin/AdminMenu.aspx")
Case "S"
Response.Redirect("Standard/StandardMenu.aspx")
Case "G"
Response.Redirect("Guest/GuestMenu.aspx")
Case Else
lblMessage.Text = SecurityLevel
lblMessage.Visible = True
Session.Clear()
End Select
End Sub

I get the error on the first line: "Dim SecurityLevel As String = mDbProcedures.Login(txtUserName.Text, txtPasscode.Text)". The pgm hits that line and stops there. Oh and mDBProcedures references another class in which I have the login function and other database procedures.

I don't know if I've explained this well. So am I getting that error because of SecurityLevel? mDbProcedures is declared and the login function is just like the other pgm with the login page that works. That's part of why I'm confused, I've copied the code from a working pgm.

Any input would be greatly appreciated. Thanks.
Incidently, I just went through it again with a breakpoint and it seems to be my mDbProcedures. In this pgm, it equals "Nothing" at that point, whereas in the pgm that works, mDbProcedures = [ProgramName].DatabaseProcedures. So somewhere I have not declared mDbProcedures properly?
okay, it appears I did not have my database procedures class declared properly. I added this to Global.asax.vb:


Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
mDbProcedures = New DatabaseProcedures("Provider=Microsoft.Jet.OLEDB.4.0;Password="""";User ID=Admin;Data Source=" & IO.Path.Combine(Server.MapPath("."), "Database\Permits.mdb") & ";")
Application.Add("mDbProcedures", mDbProcedures)
End Sub

Now it's working. So that error message means that something has not been created properly?

0 comments:

Post a Comment