Form Inheritance error with global variables in Form_Load

bit82lorry

New member
Joined
May 3, 2019
Messages
3
Programming Experience
5-10
Hi All

I am trying to resolve an "Object reference not set to an instance of an object. " during the design time.

Basically I have a base form with a button only (Form1.vb). And I have another Form2 inheriting from Form1. In the Form_Load event of Form1, I need to access to a global variable from another DLL.

If I compile and run, it works, but problem is when I try to load the form2 during design time, I get an error and the design UI doesn't load properly and show an error with the above mentioned message. Anyone with any ideas on how to resolve this kind of problem.

I have provided the source code and the solution is also provided. I am running this code base in Visual Studio 2008 Professional SP1.

Tks in advance.
 

Attachments

  • TstFormInherit.zip
    33.2 KB · Views: 47
Last edited by a moderator:
In Form1 Load event you have this code:
VB.NET:
Dim lst As IList = gReqInfo.getMyData("name")
gReqInfo is defined in ModSystem:
VB.NET:
Public gReqInfo As RequestInfo
Nowhere have you created an instance of RequestInfo and assigned to gReqInfo, therefore Form1 cannot load and Form2 cannot be designed.
 
Ok.

I have:

1. Create a Login.vb windows form. And in this form I have a button which will instantiate a new RequestInfo and assign to gReqInfo.
VB.NET:
Public Class Login

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        ''Authenticate the user.
        
        gReqInfo = New RequestInfo()

        Dim frm As New Form2
        frm.Show()

        Me.Dispose()
    End Sub
End Class
2. In Project settings, i have also set the startup form to Login.vb

But the result is still the same.

Basically I will authenticate the user using the Login.vb and if the authentication is successful, this object will be
instantiated inside Login.vb
and then accessed by all the forms in that project.
 
Last edited:
Form designer tries to load the form, and designer doesn't press that button to do it :) You could check If variable is Nothing before using it, or move the code to a separate method that you call from button.
 
I guess that too and I just come out with a workaround.

I just change the following code and everything works
VB.NET:
Public gReqInfo As New RequestInfo

I will try to create a shared procedure and see if it works as the 2nd solution.

Thks JohnH for your advice.
 

Latest posts

Back
Top