Forms access null exception.

LeoVBNET

Member
Joined
Apr 9, 2013
Messages
5
Programming Experience
5-10
Hi
This is stranged:


This first scenario works good!!!
============================================================
FORM1
F3 AS NEW FORM3
F3.SHOWDIALOG()


FRIEND SUB METHOD()
F3.BACKCOLOR = AQUA <----- (WORKS FINE)
END SUB
============================================================
FORM3
FORM1.METHOD()
============================================================


This second scenario DOES NOT work !!!
============================================================
FORM1
F2 AS NEW FORM2
F2.SHOWDIALOG()
============================================================
FORM2
F3 AS NEW FORM3
F3.SHOWDIALOG()


FRIEND SUB METHOD()
F3.BACKCOLOR = AQUA <----- F3 IS NOTHING !!!! (EXCEPTION)
END SUB
============================================================
FORM3
FORM2.METHOD()
============================================================


Sorry for this poor explanation but it is 2:10 AM


Thanks
 
The issue is related to the use, or not, of default instances. Start by reading the following blog post to get an understanding of what they are and how they work:

John McIlhinney .NUT: VB.NET Default Form Instances

To explain your issue, the first code works because the startup form for the application is the default instance of it's type. In Form3, you are referring to the default instance if the Form1 class and that is the instance of Form1 that is already displayed. In the second code, you are referring to the default instance of Form2 but it's not the default instance of Form2 that's already displayed. It's an instance that you created yourself. That means that you actually have two different Form2 instances, one of which has a reference to your Form3 instance and one that doesn't.

Basically this comes down to the fact that you can't really mix and match. If you want the convenience of being able to refer to the default instance later on then you have to use the default instance to begin with. If you don't use the default instance to start with then you can't use it later and expect it to work. There's never a need to use default instances but, whichever way you go, just be consistent.
 
Back
Top