devxlogo

Delegate Generic Event Handling

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.clsOption ExplicitPublic WithEvents txtAny As TextBoxPrivate Sub txtAny_GotFocus()	If Len(Trim$(txtAny)) > 0 Then		txtAny.SelStart = 0		txtAny.SelLength = Len(txtAny)	End IfEnd Sub' -- Save the following code in clsGenerics.clsOption ExplicitPrivate mColGenerics As New CollectionPublic 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 textboxEnd FunctionPublic Function Count() As Long	Count = mColGenerics.CountEnd FunctionPublic Sub Delete(ByVal Index As Variant)	mColGenerics.Remove IndexEnd SubPublic Function Item(ByVal Index As Variant) As clsGeneric	Set Item = mColGenerics.Item(Index)End FunctionPublic Function NewEnum() As IUnknown	Set NewEnum = mColGenerics.[_NewEnum]End Function' -- In any form or global module where you want to have ' -- this generic textboxesPrivate 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.
See also  Professionalism Starts in Your Inbox: Keys to Presenting Your Best Self in Email
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist