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
Mar 19, 1999

Delegate Generic Event Handling

It can be useful to create generic controls of similar properties. For example, if a project has 10 textboxes on different forms that need to accept numeric input only, instead of repeating the same code in every textbox, you can create a class called clsGeneric and declare the control using WithEvents. You can then trap the events in one place.

Create a collection of the clsGeneric class and keep adding controls to the collection. When you end the app, set the Collection object to Nothing. You can use control arrays, but if you're using them across the forms, you don't have to repeat the code:

 
' --- Save the following code in clsGeneric.cls
Option Explicit
Public WithEvents txtAny As TextBox

Private Sub txtAny_GotFocus()
	If Len(Trim$(txtAny)) > 0 Then
		txtAny.SelStart = 0
		txtAny.SelLength = Len(txtAny)
	End If
End Sub

' -- Save the following code in clsGenerics.cls
Option Explicit
Private mColGenerics As New Collection

Public Function Add(ByVal txtAny As TextBox, Optional _
	ByVal Key As String = "") As clsGeneric
	Dim clsAny As New clsGeneric

	Set clsAny.txtAny = txtAny
	If Key = "" Then
		mColGenerics.Add clsAny
	Else
		mColGenerics.Add clsAny, Key
	End If
	Set Add = clsAny	' Return a reference to the new textbox
End Function

Public Function Count() As Long
	Count = mColGenerics.Count
End Function

Public Sub Delete(ByVal Index As Variant)
	mColGenerics.Remove Index
End Sub

Public Function Item(ByVal Index As Variant) As clsGeneric
	Set Item = mColGenerics.Item(Index)
End Function

Public Function NewEnum() As IUnknown
	Set NewEnum = mColGenerics.[_NewEnum]
End Function

' -- In any form or global module where you want to have 
' -- this generic textboxes
Private clsTexts As New clsGenerics

' In form load add the controls to the collection like this.

	clsTexts.Add Text1
	clsTexts.Add Text2
	clsTexts.Add Text3

' You can even declare clsTexts globally and keep adding 
' controls in whatever forms needed.
Badari Syam
 
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