Click here to Skip to main content
15,886,026 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
If this sounds stupid don't down vote it please, answer it and I'll probably accept it.


So here's my problem
C#
public void btnOk_Click(object sender, EventArgs e)
{
    //when btnOk is clicked execute this
}
public void btnOk2_Click(object sender, EventArgs e)
{
    btnOk_Click(/*I don't know what to enter here for 'object sender, EventArgs e' to get to 'btnOk_Click'*/);
    
}

I know I could do this

C#
btnOk2.Click += new EventHandler(btnOk_Click);

but that doesn't work for what I want.
Any suggestions?
Posted

An important question is: Are you using the parameters in btnOk_Click?
If no, then do this:
C#
public void btnOk2_Click(object sender, EventArgs e)
{
     btnOk_Click(null,null);
}

If yes, then you need to call the method with the necessary parameters.
 
Share this answer
 
v3
Comments
Curtdawg123 10-Nov-12 13:32pm    
Okay, thanks, that makes sense
Hi,

You seem to need to execute a common code for two ButtonClick events. I think the best way is to write the code to be executed in a separate method. Let's say the method be Common_Code(). Then do the following:

btnOk.Click += new EventHandler(btnOk_Click);
btnOk2.Click += new EventHandler(btnOk2_Click);


Then do this:

C#
public void btnOk_Click(object sender, EventArgs e)
{
    this.Common_Code();
}
public void btnOk2_Click(object sender, EventArgs e)
{
    this.Common_Code();

}



While calling Common_Code() method use appropriate parameters as you might be needing. The this keyword helps you to point at the current object through which you are calling the method.

I think this will be better way to execute a common code.
 
Share this answer
 
Comments
Curtdawg123 10-Nov-12 13:34pm    
I can see what you mean, but in my program that doesn't quite fit.
Dave Kreskowiak 10-Nov-12 14:18pm    
Yes, it does fit. There is never a reason to have one evnet handler call another.

If there are other parameters that have to be passed, you can change the method header to cover those. But, since you haven't spelled out why "it doesn't fit", it's impossible to tell you how to make it work.
Ritwesh 11-Nov-12 3:06am    
If you can tell us why it 'doesn't fit' then we can probably try to find some other way to it.
Curtdawg123 17-Nov-12 10:50am    
Look at 'ProgramFox's way of doing it that was what I was looking for. Sorry if I didn't explain how it didn't fit. I'm pretty new to all this.
Ritwesh 17-Nov-12 14:52pm    
Glad you got what you wanted buddy...:-)
For the 'sender' argument, you can also use the keyword 'this', meaning that the form itself.
 
Share this answer
 
Comments
Curtdawg123 10-Nov-12 13:32pm    
Okay

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