Click here to Skip to main content
15,886,802 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
how to call different user controls from different buttons in C#.
or
how to call multiple user controls from multiple buttons in C#
Posted
Comments
_Maxxx_ 30-Jan-13 1:22am    
You don't actually call a user control - do you mean you want to execute a method of a user control when you press a button on another user control? Or do you want to instantiate a user control when you press a button?
Perhaps if you explained a little about what you are trying to achieve?

Just add a reference to the user control and then call methods of that control.

You should be able to drag and drop user controls on the form and then access them via properties as well.
 
Share this answer
 
HI,

You need to create an event handler for the button-event of the usercontrol and fire it from the click event of the actual button.

class MyControl : UserControl
{
    public delegate void ButtonClickedEventHandler(object sender, EventArgs e);
    public event ButtonClickedEventHandler OnUserControlButtonClicked;
}

Now you need to listen to the event of the actual button:

class MyControl : UserControl
{
    public delegate void ButtonClickedEventHandler(object sender, EventArgs e);
    public event ButtonClickedEventHandler OnUserControlButtonClicked;

    public MyControl()
    {
        _myButton.Clicked += new EventHandler(OnButtonClicked);
    }

    private void OnButtonClicked(object sender, EventArgs e)
    {
        // Delegate the event to the caller
        if (OnUserControlButtonClicked != null)
            OnUserControlButtonClicked(this, e);
    }
}


From the main form (owner) you can now listen to the event:
public DemoForm : Form
{
    public DemoForm()
    {
        _myUserControl.OnUserControlButtonClicked += new EventHandler(OnUCButtonClicked);
    }

    private void OnUCButtonClicked(object sender, EventArgs e)
    {
        // Handle event from here
        MessageBox.Show("Hello");
    }
}


Thanks
 
Share this answer
 
v2

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