Monday, January 18, 2010

I want to add the same event to differents controls on a form in vb.net?

I want to add the same events to a different control. So if I had to different buttons I want them to have the same functionality but then to also display there output to 2 different textBoxs'.Example


I want to look up the location of a file twice on the same form but then want the different values to be stored on the different places.I want to add the same event to differents controls on a form in vb.net?
AddHandler is the way to do this. You can use AddHandler to wire the same event handler to as many different controls as you want, provided the event signature is correct.





To do this example, add 2 buttons and 2 textboxes to the form and then paste this code in the form (assuming form is named Form1:





Public Class Form1





Public Sub New()





' This call is required by the Windows Form Designer.


InitializeComponent()





' Wire both buttons to the same event handler


AddHandler Button1.Click, AddressOf ButtonClick


AddHandler Button2.Click, AddressOf ButtonClick





End Sub





Protected Sub ButtonClick(ByVal sender As System.Object, ByVal e As System.EventArgs)


Dim buttonClicked As Button = CType(sender, Button)





Dim strMessage As String = ';Hello World! '; %26amp; buttonClicked.Name %26amp; '; was clicked!';





Select Case buttonClicked.Name


Case ';Button1';


TextBox1.Text = strMessage


Case ';Button2';


TextBox2.Text = strMessage


End Select





End Sub


End ClassI want to add the same event to differents controls on a form in vb.net?
The AddHandler method is probably best. This technique is called 'late binding', instead of binding events at design time, you do it at runtime, usually in the Form.Load event.





Unfortunately for VB.Net programmers, VB is pretty handicapped as the example you want to do is very easy in C#. Many of the code files (Such as Program.VB, which contains the entry point, and MyForm.Designer.vb) are hidden in the IDE, discouraging you from messing with that code. Normally you shouldn't do that if you don't know what you are doing, but several examples of design time modifications are not possible without being able to edit them.





Note that for most events that are EventHandler delegates, or follow that pattern, send the first parameter, sender as Object, as the control where the event is fired. So a generic event to handle drag and drop for say, a given tree control, could determine which tree control invoked the event by casting this first parameter to a TreeView. In VB this is done using the CType operator.
Try looking up the Handles option of the subroutine.





A better solution is to create a sub with parameters that can handle both conditions. Then on each control just call the sub with the approprate parameters.
  • topical cream
  • No comments:

    Post a Comment