Reputation: 2143
Hi is there a way to call the buttonclick event
in a Form
from a class which is unrelated to that form?
Upvotes: 0
Views: 278
Reputation: 329
In the class declaration i have the method ButtonClick that will be called from the form on the ButtonClick event.
class Myclass
{
public Myclass()
{
}
public void ButtonClick(object sender, EventArgs e)
{
MessageBox.Show("Button Click");
}
}
In the from you assign the event fro the button:
Myclass c= new Myclass();
button1.Click += new EventHandler(c.ButtonClick);
Upvotes: 0
Reputation: 11618
The MVP pattern is designed for this separation. That's similar to what @Jon Skeet is stating in his response, but the executing code is separated from the class.
public class Presenter
{
public void DoStuff() {};
}
public MyForm : Form
{
private Presenter presenter;
public MyForm()
{
presenter = new Presenter();
}
private void OnButtonClick(object sender, EventArgs e)
{
presenter.DoStuff();
}
}
Now you can call the click handler, but leave the form out of the invocation path.
Upvotes: 0
Reputation: 1503439
If you can get hold of the button itself (e.g. by asking the Form
for its Controls
collection etc), you can call Button.PerformClick
. I'd say this is usually a bad idea though. If the form wants to let you perform a particular action, it should expose that as a public or internal method - and then call that method from the click handler.
Upvotes: 1