Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

Hi

 

I'm really stuck on this: I want to loop through the timers on my form, and even better to be able to direct cast them from a name.

 

What I tried:

 

For Each ctrl As Control In Me.Controls

If (TypeOf ctrl Is Timer) Then

cControl.Enabled = False

End If

 

But get this error: "Expression of type 'System.Windows.Forms.Control' can never be of type 'System.Windows.Forms.Timer'. "

 

That method works perfectly for looping through buttons, textboxes... but not timers

 

Another problem is trying to DirectCast from a name to a Control. It will (again) not work with Timers.

 

I Tried:

 

Dim ctrl As Timer = Directcast("Timer1", Timer)

 

If anyone could please advise me on how to:

Loop through Timers

and how to reference timers

 

I would really appreciate it

:D

  • Leaders
Posted

First and foremost, you can not DirectCast from a name to anything. Code like the following:

Dim ctrl As Timer = Directcast("Timer1", Timer)

is bound to fail. What you are really doing there is casting the string "Timer1" to a timer, which is, of course, invalid. The string is not a timer, it is a string.

 

 

The other problem is that a timer isn't a control. It is a component. In VB6 we didn't make this distinction. In DotNet the two are different things, and components aren't stored in the control collection, they are stored in the component collection. Also, unlike a control, a component does not have a .Name property. A component is oblivious to it's design-time name, and can't be referenced by its name.

 

 

The best you can do is enumerate over components.Components and identify which ones are timers. As an alternative you could add all the timers to a collection (or a dictionary if you need to name the timers) and use that to identify all the timers.

For Each c As Component In components.Components

[sIGPIC]e[/sIGPIC]
Posted

Thanks so much for your help; Your suggestion worked perfectly!

 

To overcome the component.name peoblem, I just assigned the component.tag the same value as its name.

 

I ended up using:

 

For Each comp As Timer In Me.components.Components
                           Dim timer As Timer = comp
                          If timer.Tag = "" Then timer.Enabled = False
                       Next

:)

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...