Treating a Form Like a Function

Some forms are little more than dialog boxes that show something to the user and sometimes get something in return.

For example, I often have to create a form that displays a tabulated list box of information (say contacts). The form needs to know which item should be initially selected, and I want to know which item the user chose in the end.

Sharing of this information can be accomplished through the use of public variables, but that is not the best way of going about it.

A much better way would be to wrap the form into a function. I will show you how this can easily be accomplished.

Create a standard EXE project and add an extra form to it. Place a command button on the first form and a listbox with a button on the second.

Place this code in the first form:


private Sub Command1_Click()
    MsgBox Form2.ShowList(4)
End Sub

Place this code in the second form:



Dim iSelectedIndex as Integer

private Sub Command1_Click()
    me.Hide
End Sub

private Sub Form_Load()
    for i = 0 to 20
        List1.AddItem "Item " & i
    next i
    List1.ListIndex = iSelectedIndex
End Sub

' This is where the magic happens
' Note that we have to display a modal form to prevent
' the continuation of this function until we are ready.

public Function ShowList(Initial as Integer) as string
    iSelectedIndex = Initial                  ' Store the parameter
                                              ' for later use
    me.Show 1                                 ' Display the form
    ShowList = List1.List(List1.ListIndex)    ' Return
    Unload me
End Function

Not only does this avoid using public variables for the purpose, but we also get excellent portability since now we can just copy the form to use in a different project. None of the code is affected. We have wrapped a form into a function!



Comments

  • Great idea, here is a better implementation.

    Posted by duanerama on 05/27/2004 11:59pm

    
    ' 1.) It makes perfect sense to me to make everything like the MsgBox funtion, if there is a limited amount of input and output of the Form.
    
    ' 2.) Try something like this...
    
    ' throw this in Form1 or a class or anywhere except for in Form2 ;)
    Private Function AskForm2 (foo As String, bar As String) As String
    
      ' this way Form2 is a local variable
      ' not a global waiting for you to call it
      Dim Form2 As New Form2
    
      ' inputs
      Form2.Var1=foo
      Form2.Var2=bar
    
      ' since we need results, we should show Form2 modally
      Form2.Show vbModal
    
      ' Form2 still exists at this point
      ' you need to have all cancel/close window logic of Form2 do a Me.Hide instead of Unload Me
      ' control returns to us once the modal Form2 is Hidden
    
      ' outputs
      AskForm2=Form2.Var3
    
      Unload Form2
      Set Form2=Nothing
    
    End Function

    Reply
  • Must set to nothing

    Posted by Michel J. on 03/04/2004 09:30am

    Must set to nothingYou must set the called form to nothing:
    
    private Sub Command1_Click()
        MsgBox Form2.ShowList(4)
        Set Form2 = Nothing 
    End Sub
    
    If you don't do it, the class part of the form is always loaded into memory and local variables are set with the previous values. 
    
    Hint: when multiple values must be passed to and/or recieved from the form use XML String: 
    
    'Form1 code:
    Option Explicit
    
    Private m_xDoc As MSXML2.FreeThreadedDOMDocument
    
    Private Sub Command1_Click()
        Dim sReturn As String
        Dim xRetDocument As MSXML2.FreeThreadedDOMDocument
        
        'm_xDoc is another DOM Document containing the data
        'you want to pass the Form2.
        sReturn = Form2.ShowList(m_xDoc.xml)
        Set Form2 = Nothing
    
        If Len(sReturn) Then
            Set xRetDocument = New MSXML2.FreeThreadedDOMDocument
            xRetDocument.loadXML sReturn
            
            'Do what you want with the returned data...
        
        End If
    
    End Sub

    Reply
  • list box in a subform

    Posted by Legacy on 12/25/2003 12:00am

    Originally posted by: mailoud Gerari

    thank you, as a novice, i gained a lot and changed your idea to an input box of my own.

    Reply
  • bad idea

    Posted by Legacy on 02/13/2001 12:00am

    Originally posted by: Matt Bradbury

    this is a very bad idea. To use a public function in the form means that the form will be loaded into memory all the time. Not to mention the fact that a function declared as a string will take up the same amount of memory that a global variable in a module somewhere would, so if you are looking for a better way to do this then stick with storing the value in a global string ... granted if you find yourself writing the same code to modify that string everytime you use it then perhaps you should set up a local sub or function in that form to edit the string before you store it in the variable.

    Reply
  • Treating a Form Like a Function

    Posted by Legacy on 05/17/1999 12:00am

    Originally posted by: Mike

    Correct me if I am wrong, but isn't it impossible to have a Public Function in a Form? If that's the case than their is a HUGE error in the article "Treating a Form Like a Function".

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • With JRebel, developers get to see their code changes immediately, fine-tune their code with incremental changes, debug, explore and deploy their code with ease (both locally and remotely), and ultimately spend more time coding instead of waiting for the dreaded application redeploy to finish. Every time a developer tests a code change it takes minutes to build and deploy the application. JRebel keeps the app server running at all times, so testing is instantaneous and interactive.

  • The exponential growth of data, along with virtualization, is bringing a disruptive level of complexity to your IT infrastructure. Having multiple point solutions for data protection is not the answer, as it adds to the chaos and impedes on your ability to deliver consistent SLAs. Read this white paper to learn how a more holistic view of the infrastructure can help you to unify the data protection schemas by properly evaluating your business needs in order to gain a thorough understanding of the applications …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds