Square Ponge
Square Ponge

Reputation: 762

Usercontrol handle in Form not Firing

I create a event and handle it on the Form

User Control Code:

public event EventHandler ButtonClick;
private void button1_Click(object sender, EventArgs e)
    {
        if (this.ButtonClick != null)
            this.ButtonClick(sender, e);        
    }

Form Code:

private Usercontrol1 sampleUserControl = new Usercontrol1();
public Form1()
    {
        InitializeComponent();
        sampleUserControl.ButtonClick += new EventHandler(this.UserControl_ButtonClick);
    }
private void UserControl_ButtonClick(object sender, EventArgs e)
    {
        //sample event stuff
        this.Close();
        Form2 F2 = new Form2();
        F2.Show();
    }

but the event does not firing. What must be the problem?

Upvotes: 0

Views: 438

Answers (3)

Square Ponge
Square Ponge

Reputation: 762

public Form1()
{
    InitializeComponent();
    this.Usercontrol11.ButtonClickEvent += new EventHandler(UserControl_ButtonClick);
}
private void UserControl_ButtonClick(object sender, EventArgs e)
{
    //sample event stuff
    this.Close();
    Form2 F2 = new Form2();
    F2.Show();
}

Usercontrol1 is the name of usercontrol. So when I add the usercontrol1 to form i gives me the name Usercontrol11

Upvotes: 0

Hans Passant
Hans Passant

Reputation: 942438

 private Usercontrol1 sampleUserControl = new Usercontrol1();

It isn't terribly obvious exactly what button you clicked, but it won't be the button on that user control. You never added it to the form's Controls collection so it is not visible. Fix:

public Form1()
{
    InitializeComponent();
    this.Controls.Add(sampleUserControl);
    sampleUserControl.BringToFront();
    sampleUserControl.ButtonClick += new EventHandler(this.UserControl_ButtonClick);
}

With some odds that you now have two of those user controls on your form. One that you previously dropped on the form, possibly with the name "Usercontrol11". And the one you added in code. Either use the designer or write the code, doing it both ways causes this kind of trouble.

Upvotes: 2

No Idea For Name
No Idea For Name

Reputation: 11607

i've taken your code and compiled it and the event fired right off, so my answer is that the ButtonClick event that you created and fired in the method button1_Click isn't called because the method is not connected to the event of the button clicked for some reason.

please check that the method is called and that the event ButtonClick have been registered on the moment the method button1_Click was called. if the method was not called, you haven't registered the button1_Click method. otherwise, you might have registered to some other item

Upvotes: 1

Related Questions