tags:

views:

43

answers:

2

I have a Panel which contains 20 PictureBox controls. If a user clicks on any of the controls, I want a method within the Panel to be called.

How do I do this?

public class MyPanel : Panel
{
   public MyPanel()
   {
      for(int i = 0; i < 20; i++)
      {
         Controls.Add(new PictureBox());
      }
   }

   // DOESN'T WORK.
   // function to register functions to be called if the pictureboxes are clicked.
   public void RegisterFunction( <function pointer> func )
   {
        foreach ( Control c in Controls )
        {
             c.Click += new EventHandler( func );
        }
   }
}

How do I implement RegisterFunction()? Also, if there are cool C# features that can make the code more elegant, please share.

+6  A: 

A "function pointer" is represented by a delegate type in C#. The Click event expects an delegate of type EventHandler. So you can simply pass an EventHandler to the RegisterFunction method and register it for each Click event:

public void RegisterFunction(EventHandler func)
{
    foreach (Control c in Controls)
    {
         c.Click += func;
    }
}

Usage:

public MyPanel()
{
    for (int i = 0; i < 20; i++)
    {
        Controls.Add(new PictureBox());
    }

    RegisterFunction(MyHandler);
}

Note that this adds the EventHandler delegate to every control, not just the PictureBox controls (if there are any other). A better way is probably to add the event handlers the time when you create the PictureBox controls:

public MyPanel()
{
    for (int i = 0; i < 20; i++)
    {
        PictureBox p = new PictureBox();
        p.Click += MyHandler;
        Controls.Add(p);
    }
}

The method that the EventHandler delegate points to, looks like this:

private void MyHandler(object sender, EventArgs e)
{
    // this is called when one of the PictureBox controls is clicked
}
dtb
A: 

As dtb mentioned you definitely should assign the EventHandler as you create each PictureBox. Additionally you can use a lambda expression to do that.

public MyPanel()
{
    for (int i = 0; i < 20; i++)
    {
        PictureBox p = new PictureBox();
        var pictureBoxIndex = i;
        p.Click += (s,e) =>
        {
            //Your code here can reference pictureBoxIndex if needed.
        };
        Controls.Add(p);
    }
}
juharr
Keep in mind that the lambda expression captures the variable `i`, not the value of the variable `i`.
dtb
@dtb Yeah, I've updated to show how to get the value instead.
juharr