How do I access the event clik of a button that is in a User Control from a Form?

0

I have a UserControl with a button (and several other things, but the important thing here is that button). In execution, for some action, the program places this UserControl in a FlowLayoutPanel of Form , once set this UserControl , I need that when the user presses the button in question the UserControl do certain actions in the Form .

The normal thing would be that in the design part when doing "double click" the clik event is automatically generated in UserControl , this does, but I need to have that event Click in Form and not in the UserControl .

    
asked by JaviYeri 11.06.2018 в 08:44
source

1 answer

3

You have two options:

  • Put the button as public (you can do it from the properties of the button, changing Modifiers from Private to Public ). That way, you can subscribe to the event from the form, doing something like flowLayoutPanel.usercontrol.boton.Click += new System.EventHandler(this.boton_Click);

  • Create a custom event in your UserControl , shoot it when you press the button on it and subscribe to that custom event from your form.

  • edited

    It seems from your comment that the problem besides what you indicate is that the user controls are adding them at runtime. In this case, what you must do to subscribe to the Click of the button is to first search for the user controls by accessing the property Controls of FlowLayoutPanel , to later go through each of them and subscribe to the event. It would be something like this:

    var controles=this.flowLayoutPanel.Controls.OfType<tuControldeUsuario>();
    foreach (var controlUsuario in controles)
    {
        controlUsuario.boton.Click += ControlUsuario_Click;
    }
    
        
    answered by 11.06.2018 / 09:05
    source