Developer

Sharing the event logic between controls in VB.NET

Whenever you write the code logic that may be used for more than one control, it makes sense to try to save time by creating only one procedure that will handle the event and perform that logic. Here's how to share the event logic for multiple controls on a VB.NET form.

Whenever you write the code logic that may be used for more than one control, it makes sense to try to save time by creating only one procedure that will handle the event and perform that logic. In this tip, I show you a way to share the event logic for multiple controls on a VB.NET form.

Multiple controls in the same code

In order to facilitate development, save time, and make modifications in one place instead of many spots, it's a good idea to implement a procedure that will work the same way for multiple controls and multiple events.

In this example, I'll add three textboxes to the form by adding the following code:

Private Sub TextBoxesChanges(ByVal sender As Object, ByVal e As System.EventArgs) _

    Handles TextBox1.Leave, TextBox2.Leave, TextBox3.Leave

        Dim txtBox As TextBox

        txtBox = CType(sender, TextBox)

        MsgBox(txtBox.Text)

    End Sub

The procedure defined handles the Leave event of all TextBoxes. I create a variable to refer to the control, and then I set the variable to the control for which the event has fired. Finally, I display the Text property value of that variable in the message box.

Note: In my example, I use the same type of control (TextBox), but you could have the same functionality for different controls and handle them the same way. You could also handle different events in the same Sub even though in my example I only handled the Leave event.

Irina Medvinskaya has been involved in technology since 1996. She has an MBA from Pace University and works as a project manager at Citigroup.

————————————————————————————————————————————

Get Visual Basic tips in your inbox
Advance your scripting skills to the next level with TechRepublic's free Visual Basic newsletter, delivered each Friday. Automatically subscribe today!

Editor's Picks