User Control C #

3

I have the following user control being used in a Form:

public partial class CampoTelefone : UserControl 
{
    private void maskedTextBoxTelefone_Validating(object sender, CancelEventArgs e) 
    {
        //validações 
    }         
}

After the user populate the user control in the Form I pass it to another class that performs other types of validations, the parameter container is receiving a GroupBox :

private void valida(Control container)
{
    foreach (Control c in container.Controls.Cast<Control>().OrderBy(c => c.TabIndex))
    {
        valida(c);

        if (c is CampoTelefone && c.Tag.ToString() == "1") 
        { 
            /*outras validações*/ 
        }          
    }
}

In this part if (c is CampoTelefone && c.Tag.ToString() == "1") I need to access the properties of c which in this case is my user control, but its properties are not accessible, even passing a new instance of user control to the method that executes foreach . The properties I can access are only those I set at the time of user control implementation.

In this part of the code using the control TextBox it works correctly:

foreach (Control c in container.Controls.Cast<Control>().OrderBy(c => c.TabIndex))
{
    valida(c);
    if (c is TextBox && c.Tag.ToString() == "1")
    {
        // faço mais validacoes
    }
}

I exclude the code part of the checks by question space, and I used campoTelefone to simplify.

What would be the solution to this problem?

    
asked by anonymous 01.07.2016 / 19:58

1 answer

3

It turns out that you are asking for an instance of Control in your method, even if its object is of a type derived from it, the instance it receives will be Control .

You just need to convert this object to the type you want, see (I'll give you two conversion examples, choose the most appropriate one):

private void valida(Control container)
{
    foreach (Control c in container.Controls.Cast<Control>().OrderBy(c => c.TabIndex))
    {
        c = (CampoTelefone)c; //estoura uma exception se não for possível converter
        c = c as CampoTelefone; // c recebe null se não for possível converter

        valida(c);

        if (c is CampoTelefone && c.Tag.ToString() == "1") 
        { 
            /*outras validações*/ 
        }          
    }
}

This question can help you understand is : Difference between the use of typeof and is

    
01.07.2016 / 20:39