简体   繁体   中英

C# - How can I name a new event handler with number suffix using a variable?

I am creating new picture boxes and their click event handlers programmatically. But I can't use them seperately because I can't name them properly. I need to name the event handlers like box1_click, box2_click...

What is the simplest way to name new event handlers separately numbered with an integer?

My attempt:

for(i=1; i<11; i++)
{
   boxes[i] = new PictureBox();
   boxes[i].Name = "box" + i;
   boxes[i].Click += new EventHandler( ??? );
}

You should always use the same event handler. Inside the handler you would decide upon the sender parameter what has to be done.

There are multiple ways to do that.

You could either add the event handler as a lambda expression that calls each specific handler by reflection like this (make sure to define your handlers as public methods):

MethodInfo method = this.GetType().GetMethod("B_Click" + i.ToString());
boxes[i].Click += (o,e) =>
{
    if (null != method)
    {
        method.Invoke(this, new object[2] { o, e });
    }
};

...

 public void B_Click1(object sender, EventArgs e)
 public void B_Click2(object sender, EventArgs e)
 etc...

Another option is to create a delegate event handler using Delegate.CreateDelegate instead of a lambda expression like this:

MethodInfo method = this.GetType().GetMethod("B_Click" + i.ToString());
EventHandler handler = (EventHandler)Delegate.CreateDelegate(typeof(EventHandler), this, method);
boxes[i].Click += handler;

...

 public void B_Click1(object sender, EventArgs e)
 public void B_Click2(object sender, EventArgs e)
 etc...

Probably the best option is to define one handler for all PictureBoxes and cast sender object as the clicked PictureBox like this:

boxes[i].Click += B_Click;

...

private void B_Click(object sender, EventArgs e)
{
    PictureBox clickedPictureBox = sender as PictureBox;
    if (clickedPictureBox != null)
    {
        string name = clickedPictureBox.Name; // for example get picture box name
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM