tags:

views:

55

answers:

3

There is a private void btnContBalloon_Click(object sender, EventArgs e). Can I make this static because I want to invoke this from static method but I can not.

+1  A: 

Yes, if that method doesn't need the instance members of the enclosing class you can make it static. Nothing prevents an event handler from being static, if that is the real question.

Bottom line: If that method only uses the sender object (probably the button) and the event args or other static members, then this is perfectly valid and possible.

Benjamin Podszun
But you shouldn't invoke event handlers from context different from event handling, why not to invoke just logic inside?
Restuta
Agreed. I would be interested in the usecase as well. Although it is possible I guess the design could be improved by extracting the relevant code into a static method and calling that from both the event handler and the second (static) context.
Benjamin Podszun
@restuta invoking logic inside doesn't work so it is necessary
Harikrishna
How can it be? I don't believe you =) Show us your code please.
Restuta
you can write your own event handler why you are changing this one.
Pankaj
A: 

In general: Yes, eventhandlers can be made static. But the normal rules for static methods apply.

But often the autogenerated code gets into trouble when you change a autogenerated eventhandler to static. I'd do that with manual added eventhandlers, only.

tanascius
+1  A: 

Making events static is a great way to shoot the foot. A static event has an unlimited life-time. Which makes any event handlers you register for the event live forever too. Which makes any form that contains such an event handler live forever too. A leak.

Registering an event handler for a static event requires code in, say, the FormClosing event handler that explicitly unregisters the handler. You can see this explicitly documented in the MSDN Library article for the SystemEvents class, one of the few examples of a class in the .NET framework that has static events.

The better approach is to keep track of the form instance whose button's Click event should be activated. Something like this:

  public partial class Form1 : Form {
    public static Form1 MainForm { get; private set; }
    public Form1() {
      InitializeComponent();
      MainForm = this;
    }
    public void RunClickMethod() {
      button1.PerformClick();
    }
    protected override void OnFormClosing(FormClosingEventArgs e) {
      MainForm = null;
      base.OnFormClosing(e);
    }
  }

Which allows client code to do this:

  Form1.MainForm.RunClickMethod();
Hans Passant