954,500 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Create Button Click Event in C#

Hi Guys, Can Anybody tell me where i am wrong. The event can't be fired on clicking button6

private void button6_Click(object sender, EventArgs e)
        {
            this .button7.Click +=new EventHandler(button7_Click);
        }
        private void button7_Click(object sender,EventArgs e)
        {
            MessageBox.Show("Button7 Clicked when ur pressing button6");
        }
bhagawatshinde
Posting Whiz
313 posts since Sep 2010
Reputation Points: 21
Solved Threads: 22
 

Not sure what the problem is. Clicking on button6 adds a click handler for button7. Clicking on button7 should fire the handler.

Momerath
Nearly a Senior Poster
3,384 posts since Aug 2010
Reputation Points: 1,232
Solved Threads: 558
 

I don't know what you are trying to accomplish.

If you want to call the button7_Click() method when button6 is clicked then you can do it like this:

private void button6_Click(object sender, EventArgs e)
 {
     button7_Click(null, null);
 }
farooqaaa
Posting Whiz in Training
295 posts since Jul 2008
Reputation Points: 61
Solved Threads: 71
 

What farooqaaa said is correct of course. But, if you want to call the Click event of a control, without knowing which method is handling the event (e.g. event handler was changed), you have to inherit the control and expose the OnClick() method. For example:

public class MyButton : Button
{
    public void ClickMe()
    {
        OnClick(null);
    }
}

Events can only be invoked by the declaring class, even inherited classes cannot.

nmaillet
Posting Whiz in Training
236 posts since Aug 2008
Reputation Points: 69
Solved Threads: 53
 

Why would you do an even for some button inside other button? This makes no sence.
Events for all the button can be generated on the load time. Or when you create some button in the run time (afterwards).

If you still inisit you can do it:

private void button6_Click(object sender, EventArgs e)
        {
            //just make sure your button initialized on form!!
            this.button7.Click += new EventHandler(button7_Click);
            EvenArgs ee = new EventArgs();
            button7_Click(this.button7, ee); //this will fire button event!
        }
        private void button7_Click(object sender,EventArgs e)
        {
            MessageBox.Show("Button7 Clicked when ur pressing button6");
        }
Mitja Bonca
Nearly a Posting Maven
2,485 posts since May 2009
Reputation Points: 641
Solved Threads: 474
 

Thanks all for replying such wonderful guidance. Mitja Bonca this is working fine for me.

bhagawatshinde
Posting Whiz
313 posts since Sep 2010
Reputation Points: 21
Solved Threads: 22
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You