Forms, Controls, and Other Useful Objects - 4.3 Sharing Event-Handler Logic Among Many Controls (Page 3 of 5 )
Problem
You have many controls that should use identical event-handler logic for some of their events. You don’t want to rewrite the logic for each control. You accomplished this in Visual Basic 6.0 using control arrays, but they no longer exist in Visual Basic 2005.
Solution Sample code folder: Chapter 04\SharingControlLogic
You can use a single .NET method as the event handler for any number of control events on the form, as long as those events share a common set of event arguments.
Discussion Visual Basic 6.0 included a feature called control arrays that allowed developers to share a single event-handler procedure among multiple controls. The controls in the array had to be of the same type and share a common name. They differed only by the values of their numeric Index properties. Each event handler also included an extra argument that identified the index of the control triggering the event.
Visual Basic in the .NET world no longer allows control arrays, but you can still share event handlers. To do this, you alter the event method’sHandlesclause to include all the control events it should handle.
Create a new Windows Forms application, and add three newTextBoxcontrols toForm1. By default, they are namedTextBox1,TextBox2, andTextBox3. Add aLabelcontrol namedShowInfo. Then add this source code to the form’s code template:
Private Sub MultipleEvents(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles _
TextBox1.Enter, TextBox2.Enter, TextBox3.Enter, _
TextBox1.TextChanged, TextBox2.TextChanged, _
TextBox3.TextChanged
' ----- Report the current status of this field.
Dim activeControl As TextBox
activeControl = CType(sender, TextBox)
ShowInfo.Text = "Field #" & _
Microsoft.VisualBasic.Right(activeControl.Name, 1) & _
", " & activeControl.Text.Length & " character(s)"
End Sub
Run this program. As you move from text box to text box and type things in, theShowInfolabel updates to show you which text box you are in (based on the number extracted from its control name) and the length of its content. Figure 4-3 shows the form in use.

Figure 4-3. A single event handler dealing with multiple events
See Also Recipes 4.1 and 4.2 also discuss features that are replacements for Visual Basic 6.0 control arrays.
Next: 4.4 Working with Timers >>
More Visual Basic.NET Articles
More By O'Reilly Media
|
This article is excerpted from chapter four of the Visual Basic 2005 Cookbook, written by Tim Patrick and John Clark Craig (O'Reilly; ISBN: 0596101775). Check it out today at your favorite bookstore. Buy this book now.
|
|