Click here to Skip to main content
15,913,486 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I added a usercontrol to my C# project and added a buttonsX to the usercontrol.
In my main form, I have a buttonY that populates a listbox also in the main form.
How can I invoke the buttonY from buttonX?

What I have tried:

trying to learn the invoke method but it is very complex
Posted
Updated 13-Jul-17 18:26pm

Simple. You don't.

The problem with what you're describing is that you're tying the UserControl to the form forever. It will not be able to be used in any other form. Controls should NEVER know anything or want to do anything with the parent container (Form or other controls). Controls are responsible only for their own content and code.

So how do you do this? Your UserControl should expose an event that your button code raises. The parent form, or other containing control, can subscribe to this event and decide what to do when the event is raised, for example, running that button code, or even ignoring the event.

The other problem with what you describe is that the code in the Button Click handler that you want to run should not be in the Button Click event handler. That code should be in its own method, making it very easy to call it from both the Button Click event handler AND anywhere else in the Form code, even the event handler for your UserControl Button event.
 
Share this answer
 
// user control button click event
       private void buttonsX_Click(object sender, EventArgs e)
       {
           Button parentFormButtonY = (Button) this.ParentForm.Controls.Find("buttonsY", true)[0];
           parentFormButtonY.PerformClick();

       }
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900