Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Visual Basic
Expertise: Intermediate
Feb 24, 2000

Treat a Form Like a Function

Some forms are merely dialog boxes that show something to the user and sometimes get something in return. For example, you might have to create a form that displays a tabulated listbox of information—contacts, for example. The form needs to know which item should be selected initially, and you want to know which item the user chose in the end. You can share this information through public variables, but wrapping the form into a function proves a better way. 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
Private Sub Command1_Click()
	Me.Hide
End Sub
Private Sub Form_Load()
	Dim i As Long
	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 vbModal
	' Display the form
	ShowList = List1.List(List1.ListIndex)
	' Return
	Unload Me
End Function
This technique not only lets you avoid using public variables, but it also gives you excellent portability because you can simply copy the form into a different project. None of the code is affected. You have wrapped a form into a function.
Konstantin Komissarchik
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

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