Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

create MouseOver event at runtime...

Status
Not open for further replies.

lidds

Programmer
Jun 9, 2005
72
GB
I have a form that depending on results from a table would create a number of buttons using code at runtime. This could range from 1 to 20 buttons. What I am struggling with is creating a generic mouse over event for each of these buttons? The reason why I want a generic mouseover event is that depending on the text on the button I would do certain things, instead of duplicating the same code in individual mouseover events.

Is anyone able to give me some help with this. I am writing in VB.Net

Thanks in advance

Simon
 

While you can "write" code at runtime, it is a very convoluted process that I have found to usually be more trouble than it is worth.

What you can do easily is this:

1) Create an event handler for the event(s) in question. For this example I am using MouseHover:

Code:
Private Sub Button_MouseHover(ByVal sender As Object, ByVal e As System.EventArgs)
        'your code here
End Sub

Note that there is no "Handles" statement at the end of the method signature.

2) When you create the buttons, assign the event handler above to the appropriate event on the button:

Code:
AddHandler Button1.MouneHover, AddressOf Button_MouseOver

Event handlers in .NET can handle events for multiple controls; you could have all 20 buttons connected to this one event handler. You can differentiate between the controls in the event handler code via the "sender" parameter:

Code:
If sender.Name = "Button1" Then
    'do something
ElseIf sender.Name = "Button2" Then
    'do something else
...
...
...
EndIf

You could also use a Select Case block rather than If...Then.

I used to rock and roll every night and party every day. Then it was every other day. Now I'm lucky if I can find 30 minutes a week in which to get funky. - Homer Simpson

Arrrr, mateys! Ye needs ta be preparin' yerselves fer Talk Like a Pirate Day!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top