Can I use multiple handles all tied to one click event routine?

J

JamesL

I created one button and programmed it to a simple form change. I then
copied that button and pasted it several times. After this, I noticed that
in the code, VisualStudio had tied all of the buttons to the same click
event routine with each button listed sequentially in the handles.
The code as it appeared is:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles cmd1.Click, cmd2.Click, cmd3.Click, cmd4.Click

Dim frmTablet As frmTablet

frmTablet = New frmTablet

frmTablet.Text = cmd1.Text

frmTablet.Show()

End Sub

I want each of these buttons to open the same form, but I want the text from
the button to appear at the top of the form. I was going to call a
subroutine from the click event of each individual button and pass the text
property to the subroutine. But after seeing this I am wondering...
Can I leave all the buttons tied to the same Click event routine using the
handles as they appear here? And if so, how can I pass which button
triggered the event in order to select the correct text property? Is it as
simple as replacing cmd1.text above with Button1.text? Or do I need to
somehow add the button text property to the arguments in the routine?

If I can do this in this manner it would save a lot of code because I have
24 buttons to do this with.

James
 
T

Tim Wilson

A reference to the Button that raised the event is past as the "sender".
Just cast the "sender" argument as a Button and then access its Text
property.
 
J

Johann Granados

Hi James,

Of course you can leave the click event for all buttons linked to the same
method. The sender object passed as parameter represents the object that
fired the event. All you have to do is casting the sender object to the
correct type before using it. In your case:

frmTablet.Text = CType(sender,Button).Text

Johann Granados
MVP .NET Compact Framework
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top