Question

I know the standard code for a button click in the Form.Designer.cs is:

this.button1.Click += new System.EventHandler(this.button_Click);

And the standard code in the form:

private void button_Click(object sender, EventArgs e)
        {
        }

What's the way to pass a variable from the Form.Designer.cs to the Form? Is it possible to write:

private void button_Click(object sender, EventArgs e, int variable)
        {
        }

In the form designer I tried writing

this.button1.Click += new System.EventHandler(this.button_Click(,,1);

but it asked me to declare object sender and EventArgs e, and for both I didn't know what to put.

Was it helpful?

Solution

The signature of the event handlers of standard controls cannot be changed from what the NET Framework programmers have established to be.
A Button Click event (as well every other event handler for the standard controls) always receive two parameters, the first is the sender (or the controls that originates the event, the second is a simple EventArg or another more complex class when more details are required to handle the event.

You cannot change that. Keep in mind that is the framework code that calls that event handler, not you. How could the framework know that you want to pass an extra variable and change its code on the fly to adapt to your request?

If you want to share the same event handler between multiple buttons, there are numerous way to recognize the button clicked.

First, the most clean way, every button has a name

private void button_Click(object sender, EventArgs e)
{
    // I assume that only buttons are assigned to this event
    Button btn = sender as Button;
    if(btn.Name == "button1")
       ,,,,
    else
       ...
}

Another way is through the Tag property. You set this property to the value you require using the Form Designer or in code. Using code you could also set the Tag property to something more complex than a string

...
MyClass c = new MyClass();
button1.Tag = c;
....

private void button_Click(object sender, EventArgs e)
{
    Button btn = sender as Button;
    MyClass t = btn.Tag as MyClass
    if(t != null) 
       ......
}

OTHER TIPS

The simplest way adding another method and do your implementation inside of it.For example add this method for event handler:

private void button_Click(object sender, EventArgs e)
{

}

Then attach the event handler:

this.button1.Click += new System.EventHandler(this.button_Click);

Then add another method that takes parameter you want to pass:

private void button_ClickImpl(object sender, EventArgs e, int variable)
{

}

And then inside of your button_Click event you can call this method with passing your arguments, for example:

 private void button_Click(object sender, EventArgs e)
 {
     button_ClickImpl(sender, e, 2323);
 }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top