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: VB.NET
Expertise: Intermediate
Dec 1, 2001

Adding events dynamically in a Windows Form

The new AddHandler statement makes it possible to attach event dynamically, that is without having to bind them via static code based on the Handles keyword. This keyword is also useful to have all the controls on a form share the same event procedure.

For example, say that you want to change the background of all textbox controls on the form when the focus enters in them, and restore the original color when the focus leaves them. Here's the code code that does the trick:


Sub SetupEventHandlers()
    Dim ctrl As Control
    For Each ctrl In Me.Controls
        If TypeOf ctrl Is TextBox Then
            AddHandler ctrl.GotFocus, AddressOf Controls_GotFocus
            AddHandler ctrl.LostFocus, AddressOf Controls_LostFocus
        End If
    Next
End Sub

Private Sub Controls_GotFocus(ByVal sender As Object, _
    ByVal e As System.EventArgs) 
    Dim ctrl As Control = CType(sender, Control)
    ' In a real application you should use system-defined colors.
    ctrl.BackColor = Color.Yellow
End Sub

Private Sub Controls_LostFocus(ByVal sender As Object, _
    ByVal e As System.EventArgs) 
    Dim ctrl As Control = CType(sender, Control)
    ' In a real application you should use system-defined colors.
    ctrl.BackColor = Color.White
End Sub

Francesco Balena
 
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