tags:

views:

126

answers:

2
    private void changeFont()
    {
        Control.ControlCollection controls = tabControl1.Controls;
        foreach (Control control in controls)
        {
            TabPage t = (TabPage)control;
            Control c = t.GetChildAtPoint(new Point(250, 250));
            System.Type type = typeof(c);  //-->1st error
            ((type)c).changeFont(fontModifier); //-->2nd error
        }
    }

Error 1 The type or namespace name 'c' could not be found (are you missing a using directive or an assembly reference?) Error 2 The type or namespace name 'type' could not be found (are you missing a using directive or an assembly reference?)

What's wrong with it? Just for the context, i'm trying to go through the tabcontrol and in each tabpage we have a user control, so that's why the getChildAtPoint is that particular position. In all the usercontrols, we have a changefont function that'll change the size of the font of specific controls....

Thanks :)

+2  A: 

To get the actual type of an object, instead of typeof, which gets the type for a type name (as in typeof(string)), you need to use c.GetType(), which gets the actual type of the object pointed by c.

As for (type)c, you can't do that: type casting works only by using a specific type name. If you need to invoke the changeFont method only in controls that are of, or derive from your custom control type, you should do:

if(typeof(MyControlType).IsAssignableFrom(c.GetType()) {
    ((MyControlType)c).changeFont(fontModifier);
}

Or, even easier:

var myControl = c as MyControlType;
if(myControl != null) {
    myControl.changeFont(fontModifier);
}
Konamiman
the first one works, thanks :)the second one however...i have: System.Type Type = c.GetType(); ((Type)c).changeFont(fontModifier);was that what you meant? because visual studio thinks that Type (2nd line) is refering to System.Type rather than the variable.
ladidadida
By the way where is the `changeFont` method defined?
Konamiman
in my user defined controls
ladidadida
On your last line you have to cast it to a specified type to be able to call methods for that type.
ck
that's why i was trying to do the (type)c.changeFont(.....) thing... but i guess i did it wrong?
ladidadida
so i have to make them all part of the same interface or something? Thanks
ladidadida
yes ladidadida, and all of those controls should implement changeFont
PoweRoy
A: 

if all the usercontrols have a changeFont function, I presume implementation of a class/interface.

private void changeFont()
{
    Control.ControlCollection controls = tabControl1.Controls;
    foreach (Control control in controls)
    {
     TabPage t = (TabPage)control;
     Control c = t.GetChildAtPoint(new Point(250, 250));
     if (c is <your class>)
     {
      (<yourclass>)c.changeFont(fontModifier);
     }
    }
}
PoweRoy
Thanks for this :)
ladidadida