
Windows Forms - Loading & Unloading Forms
Quote:
> This is easy in vb6, but for some reason they seem to
> have made it harder.
The very fact that you do not realize why they made it 'harder' is the main
reason why they made it like it is.
See in VB6 there was a global variable in the project that represented each
form. These were not instanciated at program startup. Global variables of
this nature are questionnable to begin with. For example, how would you show
two instance of the same form using this technique?
VB6 went further in it's quest to make things easier by automatically
instanciating a form object when the un-instanciated variable was accessed.
Although it makes things easier it's a very awkward way of doing things. One
case where this can get very dangerous and completly loose a newbie is this:
- You have a main form called frmMain.
- You have another form called frmInput which contains an editbox, an OK
button, a Cancel button and finally a public member variable of boolean type
which is called blnOkPressed.
- On OK, blnOkPressed= true, and Unload Me is called
- On Cancel, blnOkPressed= false, and Unload Me is called
In the main form, some bit of code would call this to get a value :
Public sub MySub
frmInput.Show vbModal
if frmInput.blnOkPressed then
MsgBox frmInput.myEditBox.Text
end if
End Sub
Try it and see what it does. That message box will NEVER be shown. Why?
Because Unload Me uninstanciated the form (you loose any data inputed in the
form). That ain't too bad, cause it's your error, you actually called Unload
me, and you should have called Hide... This is where it gets tricky... The
'if frmInput.blnOkPressed' should in my opinion throw some kind of
exception, but instead it creates a new instance without anyone's consent,
and blnOkPressed is initialized to false, and everything runs seemingly
well........
This is the kind of error a newbie can spend alot of time
debugging..........
In the new VB, YOU instanciate any form you want to show. If you don't the
program blows in your face and you clearly see your error. There's no more
global variable either which is great cause promoting the use of global
variables to newbies really isn't all that great unless you plan on a Cobol
carreer or something :)
So there is a reason why they've made it 'harder'. I was extremely happy to
see this 'feature' removed cause it was simply a ver bad habit even if you
know what you're doing!
Alex.