Peter Olson
Peter Olson

Reputation: 143017

Binding a Method to an Event in C# with += operator

I was making a windows form, and I was trying to manually bind a method to the click event of myButton, like this:

    public Form1()
    {
        InitializeComponent();
        myButton.Click = new EventHandler(ShowMessage("You clicked my button!"));
    }

    private void ShowMessage(string message)
    {
        MessageBox.Show(message);
    }

As some of you might guess, the compiler didn't like this. I wasn't sure why, because I am used to being able to do things in Javascript like this:

document.getElementById("myButton").onclick = function(){showMessage("You clicked my button")};
function showMessage(message) {
  alert(message);
}

I muddled through it and eventually ended up doing something really ugly involving a global variable like this:

    string message = "";
    public Form1()
    {
        InitializeComponent();
        message = "You clicked my button!";
        myButton.Click += ShowMessage; 
    }

    private void ShowMessage(object sender, EventArgs e)
    {
        MessageBox.Show(message);
    }

Here are my two questions: first, is there a cleaner way to do this? Second, why do event methods have to be assigned with a += and not just an =?

Upvotes: 3

Views: 18506

Answers (6)

Adrian10 BEN
Adrian10 BEN

Reputation: 1283

You can use also lambda.

myButton.Click += (sender, e) => {
    MessageBox.Show("You clicked my button!");
};

Upvotes: 9

Doc Brown
Doc Brown

Reputation: 20054

Try this solution to get around the need of a global variable, with the possibility of having a named, reusable method for your event handler:

private void ShowMessage(object sender, EventArgs e, string message)
{
    MessageBox.Show(message);
}


public Form1()
{
    InitializeComponent();
    myButton.Click += delegate(object sender, EventArgs e)   
    { 
        ShowMessage(sender,e,"You clicked my button!");
    };  
}

Upvotes: 1

MerickOWA
MerickOWA

Reputation: 7612

Because more than one handler can be added, were as in your javascript code, only one function will be called in onclick.

Example:

myButton.Click += ShowMessage;
myButton.Click += LogToFile;

Both functions ShowMessage and LogToFile would get called when a button click happens. This is what the "+" in "+=" is trying to indicate. You're adding to the handler, not replacing it.

As far as making it easier, you would use anonymous lamdas to help like, but note that it makes it harder to detach/remove the handlers later (if thats important).

myButton.Click += new EventHandler( (sender,e) => ShowMessage("You clicked my button!") );

Upvotes: 1

Mark Cidade
Mark Cidade

Reputation: 100037

You can type myButton.Click += delegate { showmessage("You clicked my button!"); };

Upvotes: 2

kqnr
kqnr

Reputation: 3596

Event handlers must be added to events with += because the event may have multiple other delegates unknown to your particular piece of code. Pure assignment would imply an ability to remove other associated delegates, something you should not have permission to do as a client of the event.

Additionally, you probably want to take advantage of anonymous delegates to accomplish any form of argument binding. For example:

myButton.Click += delegate(object sender, EventArgs e) {
    MessageBox.Show("You clicked my button!");
};

Upvotes: 10

RvdK
RvdK

Reputation: 19800

Here are my two questions: first, is there a cleaner way to do this?

yes anonymous functions, just like in JavaScript (other syntax)

myButton.Click += delegate(object sender, EventArgs e)   
{ 
  MessageBox.Show(message);
};  

why do event methods have to be assigned with a += and not just an =?

Else you can have only 1 eventhandler instead of multiple ones to the same event. += is used a lot in programming language to add something. = is used to set the variable to a value.

Upvotes: 4

Related Questions