Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

cycle through all control instances 1

Status
Not open for further replies.

voodoojon

Technical User
Dec 18, 2003
107
0
0
GB
I have a class that extends usercontrol called PaintControl. I dragged a few of these paintcontrols onto my form. When I wanted to run the same bit of code, I used

Code:
foreach( PaintControl ctl in Usercontrols){
ctl.dosomething();
}
This worked fine, but when I dragged another control (a button) onto the form, I got an error in runtime telling me I couldn't cast this button into type Paintcontrol.

How can I achieve what I want here, which is to cycle through all the controls of type PaintControl in the collection Usercontrols, and not any others?

Thanks in advance,

Jon

One day I will find a signature worthy of this space. That day has not yet come.
 
Hi,

With the IS operator you can test that an object is of a given type.

Ex (didn't checked the syntax):
Code:
foreach (Control formControl in Usercontrols)
{ 
   if (formControl is PaintControl)
   {
      PaintControl control = (PaintControl)formControl;
      // Dosomething here ...
   }
}

Greetz,

Geert

Geert Verhoeven
Consultant @ Ausy Belgium

My Personal Blog
 
Cheers, Geert. That was just what I needed.

Jon

One day I will find a signature worthy of this space. That day has not yet come.
 
I'd just to add:

since the code I wanted to do was specific to PaintControl, I also needed to cast the object as a PaintControl within the conditional:

Code:
     foreach (UserControl uCtl in this.Controls)
     {
           if (uCtl is PaintControl)
           {
              PaintControl pCtl = uCtl as PaintControl;
              pCtl.doSomething();
           }
     }


Jon

One day I will find a signature worthy of this space. That day has not yet come.
 
Remark:

The code I provided earlier allready contains a cast:
Code:
PaintControl control = (PaintControl)formControl;

There is no real need to cast with the AS keyword. This is used to prevent errors when invalid casts occur. But since you tested the type before, you are sure that you can type the object.



Geert Verhoeven
Consultant @ Ausy Belgium

My Personal Blog
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top