ladidadida
ladidadida

Reputation: 11

c# name or type not found

    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 :)

Upvotes: 1

Views: 489

Answers (2)

Konamiman
Konamiman

Reputation: 50323

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);
}

Upvotes: 2

RvdK
RvdK

Reputation: 19800

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);
        }
    }
}

Upvotes: 0

Related Questions