Recipe 4.3. Sharing Event-Handler Logic Among Many Controls


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.


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.


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's Handles clause to include all the control events it should handle.

Create a new Windows Forms application, and add three new TextBox controls to Form1. By default, they are named TextBox1, TextBox2, and TextBox3. Add a Label control named ShowInfo. 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, the ShowInfo label 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.

Visual Basic 2005 Cookbook(c) Solutions for VB 2005 Programmers
Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))
ISBN: 0596101775
EAN: 2147483647
Year: 2006
Pages: 400

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: