dcsimg

Treating a Form Like a Function

WEBINAR:
On-Demand

Desktop-as-a-Service Designed for Any Cloud ? Nutanix Frame


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!



Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date