Question

I'm in the middle of using Visual Basic (Visual Studio 2010) to create dynamically created controls. Essentially what I'm doing is creating a label, a textbox, a label (which will act as a stopwatch), and a button (to control said stopwatch).

Each set of controls will be arranged (and named) like this in a row:

[LABEL]  [TEXTBOX]         [TIMER]       [BUTTON]
Labelx   ParticipantNamex  RingTimerx    ControlButtonx

So for a given row, I will be look like this:

[LABEL]  [TEXTBOX]         [TIMER]       [BUTTON]
Label1   ParticipantName1  RingTimer1    ControlButton1

I've gotten the bit about creating the elements dynamically as well as creating them within in a panel with a particular number attached to the end of its name on the form that I've created. What I would like to do is wire an event for the button that was dynamically created to control the stopwatch timer that was created through the same event.

So in short, I'm asking how do you wire an event to control a particularly dynamic button?

Was it helpful?

Solution

Using an anonymous sub (VB2010 only) to write the event handler inline

Timer myTimer = New Timer
Button button = New Button
AddHandler button.Click,
    Sub(s As Object, e As EventArgs)
         ' can manipulate the Timer here 
         ' because it is captured in a closure     
         myTimer.Stop    
    End Sub

Adapted from here.

PS read more about closures from our very own Jared.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top