Find Timers by Name

2019-09-03 19:39发布

问题:

Okay I'm working with visual studio and I've hit a bit of a snag. The basic situation is I have a bunch of buttons and timers that correspond to each other. For example when button1 is clicked Timer1 should start.

Currently I'm using one method to handle all of the button clicks. Which identifies the CR (1, 2, 3, etc...) and constructs a string for the name of the correct Timer that goes along with it, dim timername as string = "timer" & cr.ToString. Then when I use Me.Controls(cr).Enabled = True it returns an a null pointer error.

I know the issue has to do with the identification of the timer, suggestions?

回答1:

You can't identify a control using a string (well, not easily). Try this.

Private Sub ButtonX_Click(sender As Object, e As EventArgs) Handles Button1.Click, Button2.Click  ' etc.
    Dim vButton = DirectCast(sender, Button)
    Select Case vButton.Name
        Case "Button1"
            Timer1.Start    ' Or stop, or whatever
        Case "Button2"
            Timer2.Start
    End Select
End Sub

You can also compare the button object itself using If vButton Is Button1, but that gets messy in VB (I remember having to use GetType and stuff like that).

However, if your code is as simple as my example, why not just use separate handlers for each button?!!



回答2:

A Timer is a Component not a Control so it will not be located in the Control Collection. This is a case where it is probably better to not use a common button click handler since it is not simplifying anything.

However, everything which inherits from Object, such as a Button, has a Tag property which you can use to associate things with that object. In form load:

Button1.Tag = Timer1
Button2.Tag = Timer2
Button3.Tag = Timer3

Then the click event:

Private Sub ButtonX_Click(... etc ) Handles Button1.Click, Button2.Click ...

   Dim thisBtn As Button = CType(sender, Button)
   Dim thisTmr As Timer = Ctype(thisBtn.Tag, Timer)

   thisTmr.Start
End Sub


标签: vb.net timer