How can I instantiate a form, have it do some processing, and then not show the form? In VB6, this was feasible, but not straight forward; but it is a simple task in .NET.
In VB6, when a form loaded, and control passed from the Form_Load Event, if you did not want it to show, you had to hide it in Form_Load and then unload it in Form_Activate. It could be a real hassle, and you could even get some unwanted "flash for the audience".
In VB.NET or C#.NET, it is not a problem. This short article will show you the code for doing it. I will instantiate a form, have it do some validation processing, and then return a True or False, to denote whether or not to actually load the form.
The code, shown below, might be called from a Tool Button or Menu Click Event to trigger the load of the form. It will only load the form if the call to the CanDisplay method returns True. If CanDisplay returns False, the form will not be shown. Since frm is a local variable, the object will pass out of scope and be Garbage Collected without ever showing the form. The code processing, done in CanDisplay could obviously be done in the CheckForLoadingForm method. However, it may well be that the processing to determine whether the form can actually do the processing, will require a "pre-process", using code that will be called again, when the form is actually shown.
Additionally, to maintain good object-oriented methodology, the method or event that is loading the form, should not have any knowledge or concern with the processing, validation, etc., done by the form. For those reasons, all code that the form needs for validation and processing will be done in the form itself. I can still use the methods in the form without showing the form because it is simply a Class, just like any other class.
| Private Sub CheckForLoadingForm() Dim frm As New frmTest If frm.CanDisplay("TestParam") Then frm.ShowDialog() End If End Sub |
| Public Function CanDisplay(ByVal UserInput As String) As Boolean ' Here we will do any procesing necessary to determine ' whether we want to actually display the form. ' This could involve validating the UserInput, other parameters, ' going to database, etc. The code below is overly simple, ' but illustrates the concept If UserInput = "ValidInput" Then Return True ' tell user to show the form Else Return False ' tell user not to show the form End If End Function |