Kountay Dwivedi
Kountay Dwivedi

Reputation: 27

How to add parameters in EventHandler

This is what i want to do:

 .... 
for(i=0;i<=99;i++)
        {
            btn[i].Click += new EventHandler(btn_Clicked,i);
        }
    }

    private void btn_Clicked(object sender, EventArgs e,int i)
    {
        compute((Button)sender, picRetrieved[i]);
    }

Please help. It is showing error. But, I want to send the value of i for further processing. Is there any way to do it?

Thank you.

Upvotes: 1

Views: 115

Answers (2)

xanatos
xanatos

Reputation: 111860

Thanks to closures and anonymous functions you can do something similar:

for(int i=0;i<=99;i++)
{
    int j = i;
    btn[i].Click += (sender, e) => 
    {
        // Very important! Here use only j, not i!
        compute((Button)sender, picRetrieved[j]);
    };
}

There is a small "problem" (that isn't a problem, it's how they are done) so that you mustn't use the i variable inside the anonymous function, but if you copy it somewhere else (j for example) then you can use j.

Upvotes: 4

Patrick Hofman
Patrick Hofman

Reputation: 156978

You can't. The signature of the event handler is fixed, you can't change it.

In this case, you could use an anonymous delegate to get what you want.

for(i = 0; i <= 99; i++)
{
    int dummy = i;
    btn[i].Click += delegate(object sender, EventArgs e)
        {
            compute(btn[dummy], picRetrieved[dummy]);
        }
}

Another option is to 'tag' the button:

for(i = 0; i <= 99; i++)
{
    btn[i].Click += btn_Clicked;
    btn[i].Tag = i;
}

private void btn_Clicked(object sender, EventArgs e,int i)
{
    Button b = (Button)sender;
    int i = (int)b.Tag;

    compute(b, picRetrieved[i]);
}

Upvotes: 2

Related Questions