Below is some code that I’m using to create objects with Visual Basic:
For indexCounter As Integer = 1 To TotalParticipants Step 1
participantClock = New Label
participantClock.Size = New Size(100, 20)
participantClock.Name = "participantClock" & indexCounter
participantClock.Location = New Point(139, (5 + ((indexCounter - 1) * 26)))
participantClock.BorderStyle = BorderStyle.Fixed3D
participantClock.TextAlign = ContentAlignment.MiddleRight
CenterPanel.Controls.Add(participantClock)
participantStop = New Button
participantStop.Size = New Size(58, 20)
participantStop.Location = New Point(245, (5 + ((indexCounter - 1) * 26)))
participantStop.BackColor = Color.Red
participantStop.ForeColor = Color.White
participantStop.Font = New Font(participantStop.Font, FontStyle.Bold)
participantStop.Text = "Stop"
CenterPanel.Controls.Add(participantStop)
participantTimer = New Timer
participantTimer.Start()
participantTimer.Enabled = True
participantTimer.Interval = 1
participantStopwatch = New Stopwatch
participantStopwatch.Start()
Next
I’m creating a label, a button, Timer, and Stopwatch. (Though I have sinking feeling I don’t need BOTH a timer and stopwatch since I’m counting time.)
What I would like to do, is create the label and set that label’s text to be the value from the stopwatch. The button that will be created will stop THAT stopwatch.
The problem that I’m having is that I cannot call the stopwatch by name since it wasn’t created yet and VB throws a hissy fit at me for it. (After all it wasn’t really declared.)
So the question becomes, how do you call the most recently dynamically created control and assign events using that control. If it’s not possible to do, I do not mind dumping the form and starting over creating 30 stopwatches instead (but I’d like to avoid that, if possible).
Thanks for any help.
I assume that you want the timer to update the label based on the value of the stopwatch. Is that right?
One thing that you might try that is a little hacky is this:
Define a storage class like so:
at the top of your form define a private list:
at the end of your for loop do this
The above code would give you access to the three objects that you need in your tick function. You will have to loop through the _storage list to find the right “set” of objects but it should work:
I didn’t try to compile that code so I’m sure there are a few typos but I think that should give you an idea of how to refer to the object without needing to use the object’s name.