views:

50

answers:

1

I have created a UserControl called AutorControl with a method to clear its textbox:

public void LimpiarAutorTextbox()
        {
            textBox1.Text = "";
        }

Then my intention is from another form with a Panal, using a for loop add X ammount of the above user control. Then I want to call the UserControls method: "LimpiarAutorTextbox" (which is just a method for clearing the text of the textbox) using a foreach loop like this, however it's not working. I'm not sure what to do in this case:

AutorControl usercontrolAutorControl = new AutorControl();

        private override void ClearControls()
        {
            txtTitulo.Text = "";

            //Panel1 will only hold controls of the same type: "AutorControl"
            foreach (Control X in panel1.Controls)
            {
                X as AutorControl;//?????? I want to access each created usercontrols' method. 

            }
        }

The panel will always hold a usercontrol of AutorControl, never anything else. How can I achieve this programatically?

Thanks.

+2  A: 

Your line here is fine:

X as AutorControl

just add:

(X as AutorControl).LimpiarAutorTextbox()

that should do the trick.

Also, I know you said that there would only be AutorControls in there, but you may want to do something more like this:

AutorControl currentControl == X as AutorControl;
if (AutorControl != null)
{
  currentControl.LimpiarAutorTextbox();
}

Or alternatively, you can change your declaration of the for foreach loop to do the cast for you:

foreach(AutorControl currentControl in form.Controls)
{
  if (currentControl != null)
  {
    currentControl.LimpiarAutorTextbox();
  }
}

Some alternatives :)

CubanX