Question How to use the timer as an array?

saichong

Member
Joined
Nov 21, 2009
Messages
10
Programming Experience
Beginner
Hello all

i have a small problem in using the timer as an array
here is my code

VB.NET:
 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim i As New Integer
        i = 1
        Dim timer(i) As Timer
        timer(i) = New Timer
        While i < 5
            timer(i).Interval = 3000 * i
            timer(i).Enabled = True
            i = i + 1
            timer(i) = New Timer
        End While
    End Sub

what i want is after the timer tick
VB.NET:
textbox1.text=i
but i dont know how and where to write this code?
 
You defined the timer initially as an array of 2 timers (0 and 1). You need to define it as an empty array then redimension and preserve it each time you want to add another timer. Here's code that works:

VB.NET:
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim i As New Integer
        i = 1
        Dim timer() As Timer
        ReDim timer(i)
        timer(i) = New Timer
        While i < 5
            timer(i).Interval = 3000 * i
            timer(i).Enabled = True
            i = i + 1
            ReDim Preserve timer(i)
            timer(i) = New Timer
        End While
    End Sub

You should also consider starting i of as zero since timer(0) is never getting set or used. If you do keep in mind that 3000 * i when i = 0 is 0...
 
thank you Mr. bdinnocenzo
but my main question is how to add the action after the timer elapsed, i mean how to use the (tick) commands

if i use the following codes, it will not work:

AddHandler timer(i).Tick, AddressOf mytimer(i)

Public Sub mytimer(ByVal i)
'do ......
End Sub
 
Not sure what you want to do...I used the Tag property to store the value (String) of i to identify the timer. I also used the first timer at index zero. I replaced a TextBox with a list box because timer(0) writes every 3 seconds which overwrite Timer(1), Timer(2), etc.

This may not be the cleanest way to do this, but not knowing what you want to do, this will at least get you started.

-Bill

VB.NET:
Public Class Form1

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim timer() As Timer
        Dim i As Integer = 0
        While i < 5
            ReDim Preserve timer(i)
            timer(i) = New Timer
            timer(i).Tag = i.ToString
            AddHandler timer(i).Tick, AddressOf Timer_Tick
            timer(i).Interval = 3000 * (i + 1)
            timer(i).Enabled = True
            i = i + 1
        End While
    End Sub

    Private Sub Timer_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs)
        ListBox1.Items.Add("Timer #" & sender.tag & ": " & Now.ToLongTimeString)
    End Sub

End Class
 
Back
Top