Hey,
How do I close a form in the Load event?
I want not to load it under certain conditions.
Thanks,
Printable View
Hey,
How do I close a form in the Load event?
I want not to load it under certain conditions.
Thanks,
Your best bet would be a Sub Main
Example:
VB Code:
Module Module1 Public Sub Main() Dim frm as new Form1 If something = True Then Application.Run(frm) Else Something else End If End Sub End Module
if you wanna use the form_load sub ...
VB Code:
[COLOR=Blue]Private Sub[/COLOR] Form1_Load([COLOR=Blue]ByVal[/COLOR] sender [COLOR=Blue]As[/COLOR] System.Object, [COLOR=Blue]ByVal[/COLOR] e [COLOR=Blue]As[/COLOR] System.EventArgs) [COLOR=Blue]Handles MyBase[/COLOR].Load [COLOR=Blue]If[/COLOR] MessageBox.Show("open the application?", Application.ProductName, MessageBoxButtons.YesNo, MessageBoxIcon.Question) = DialogResult.Yes [COLOR=Blue]Then[/COLOR] [COLOR=Green]'/// do stuff because it's ok to load[/COLOR] [COLOR=Blue]Else[/COLOR] Close() [COLOR=Blue]End If End Sub[/COLOR]
I haven't tried to do this in .NET, but in VB6, closing a form during the load event caused erratic behavior. In .NET, I expect that it might be smoother, so you might just try calling Me.Close. If that still causes errors, you could set a form level boolean variable to true, then in the Activate event you can call Me.Close if the variable is true.
Yeah, I tried me.close in the load event and it doesn't do anthing. The load event just continues. I guess i'll use a public variable and check it from the calling routine.
Thanks,
to expand on this, to avoid errors that may arise i would use the form's Activated eventQuote:
Originally Posted by dynamic_sysop
but keep in mind that you'll need to use a boolean variable to know when the form's loading or not too
VB Code:
Private mblnFormLoading As Boolean = True Private Sub Form1_Activated(...) Handles Mybase.Activated If mblnFormLoading = True Then mblnFormLoading = False If MessageBox.Show("open the application?", Application.ProductName, MessageBoxButtons.YesNo, MessageBoxIcon.Question) = DialogResult.No Then Me.Close() End If End Sub
You dont have to create an instance of the form if your not going to show it.
VB Code:
Option Explicit On Module modMain Public goForm1 As Form1 Public Sub Main() If SomeCondition = True Then goForm1 = New Form1 Application.Run(goForm1) Else 'Exit or whatever End If End Sub End Module