-1

I want to implement some Pictureboxes and when one of them is clicked, a MessageBox should appear and tell which Box is clicked.

However, I want to implement a choice how many Pictureboxes should appear. When I choose another MenuItem, then the click event will be called multiple times. I tried unsubscribing, but it doesn't work.

Here is my code:

public partial class Form1 : Form
{
    PictureBox Pbox1;
    PictureBox Pbox2;
    PictureBox Pbox3;
    PictureBox Pbox4;

    public Form1()
    {
        InitializeComponent();
        this.Text = "Picturebox";

        Pbox1 = new PictureBox();
        Pbox2 = new PictureBox();
        Pbox3 = new PictureBox();
        Pbox4 = new PictureBox();
    }

    private void Pbox_Click(object sender, EventArgs e, int nr)
    {
        MessageBox.Show("Picture number " + nr.ToString() + " is clicked");
    }

    private void toolStripMenuItem2_Click(object sender, EventArgs e)
    {
        Pbox1.Image = new Bitmap(@"Picture.png");
        Pbox1.Location = new Point(20, 40);
        Pbox1.Size = new Size(160, 120);
        Pbox1.SizeMode = PictureBoxSizeMode.StretchImage;

        Pbox1.Click += (sender2, e2) => Pbox_Click(sender2, e2, 1);
        this.Controls.Add(Pbox1); }

The rest is the same as toolStripMenuItem2.

Can you help me with this problem?

Hansch
  • 11
  • 2

1 Answers1

0

When will it be called multiple times? I guess when switching to another menu item everything should work fine. But when switching back to an item that was already clicked before, then another click handler will be registered in addition to the existing one and will call the Pbox_Click method twice.

You can try to put the event registration in the constructor method or release other click-events before re-registering them.

TWP
  • 250
  • 1
  • 5
  • 13