Click here to Skip to main content
15,885,216 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
Hi,

I have a userControl and I've buttons there, I'd like to call event click in my main form.

What I have tried:

There is what I've tried, but it doesn't work in form.

UserControl
C#
public event EventHandler ButtonClick;

        protected void Button1_Click(object sender, EventArgs e)
        {
            //bubble the event up to the parent
            if (this.ButtonClick != null)
                this.ButtonClick(this, e);
        }


Form
<pre lang="c#">GameField.ButtonClick += new EventHandler(UserControl_ButtonClick);

        protected void UserControl_ButtonClick(object sender, EventArgs e)
        {
            //handle the event 
        }


I can't see class userControl from main form. It might be cause I've a partial class.
C#
public partial class GameField : UserControl
Posted
Updated 20-Jul-20 13:59pm

See here: Transferring information between two forms, Part 2: Child to Parent[^] - it's based on forms, but it's exactly the same with Controls (Forms are derived from Control anyway!).
 
Share this answer
 
Not quite as simple as parent-child form communication. To detect a size change event from a MouseUp event in a button in the programmatically created user control I added the following code in the user control:
C#
public event EventHandler SizeChanged;

        new protected virtual void OnSizeChanged(EventArgs e)
        {
            EventHandler eh = SizeChanged;
            if (eh != null)
            {
                eh(this, e);
            }
        }


In the button MouseUp I added
private void cmdResize_MouseUp(object sender, MouseEventArgs e)
        {
            ...
            EventArgs ef = new EventArgs();
            ...
            SizeChanged(sender,null);
        }


In the form containing the User Control, the code creating the control was
C#
UserControl.UserControl NewControl = new UserControl.UserControl();
                ...
                UserControl.SizeChanged += new EventHandler(UserControl_SizeChanged);
                ParentForm.Add(UserControl);


and new function
C#
void UserControl_SizeChanged(object sender, EventArgs e)
        {
            ...
        }


is executed whenever there is a MouseUp event in the UserControl button
 
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