-1

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( ??? );
}
redo
  • 1
  • 1
  • maybe this helps(duplicate?)http://stackoverflow.com/questions/1389543/c-sharp-anonymous-functions-and-event-handlers – huseyin tugrul buyukisik Feb 12 '17 at 10:19
  • Will your different event handlers share the same behavior on different PictureBoxes ? In this case, one single event handler may fit in which you get the appropriate PictureBox with: *PictureBox ThePictureBox=(PictureBox)Sender*. – Graffito Feb 12 '17 at 10:21

2 Answers2

1

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

JeffRSon
  • 10,404
  • 4
  • 26
  • 51
1

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
    }
}
Ofer Barasofsky
  • 251
  • 2
  • 8
  • Thanks!! Getting the name of clicked picture box solved my problem. Now I can use all picture boxes for separate tasks. (I used last option.) – redo Feb 12 '17 at 11:48