简体   繁体   中英

c# Dynamically creating an EventHandler in a loop

I am trying to dynamically create an array of images on a form. THe images are rendering okay, but I cannot work out how to create the eventHandlers.

    pictureBox.Click += new System.EventHandler(this.pictureBox);

This line is causing be problems.

 private void frmBorderlessMain_Load(object sender, EventArgs e)
   {
       int top = 10;
       int left = 10;
       int width = 200;
       int height = 150;
       var uutNames = MyObject.GetNames().ToArray();
       var uutImages = MyObject.GetImages().ToArray();
       for (int i = 0; i < uutNames.Length; i++)
       {
           System.Windows.Forms.PictureBox pictureBox = new System.Windows.Forms.PictureBox();


           Image newImage = Image.FromFile(uutImages[i]+".png");
           pictureBox.Image = ((System.Drawing.Image)(newImage));
           pictureBox.Location = new System.Drawing.Point(left, top);
           pictureBox.Name = "pictureBox"+i;
           pictureBox.Size = new System.Drawing.Size(200, 150);
           pictureBox.SizeMode =   
                     System.Windows.Forms.PictureBoxSizeMode.Zoom;
           pictureBox.TabIndex = i;
           pictureBox.TabStop = false;

           pictureBox.Click += new System.EventHandler(this.pictureBox);
           this.tabPage1.Controls.Add(pictureBox);
           left += width + 10;
           if ( (i > 0 ) && (i % 3) == 0)
           {
                    top += height + 10;
                    left = 10;
           }
       }
   }

Additional Info: Upon clicking the image I would like a new form to open displaying details about the entity that was clicked. It will be the same form, but will be loaded with data depending on which image was clicked on.

pictureBox.Click += new System.EventHandler(this.pictureBox);

That is not how event handlers are used.

Lambda:

pictureBox.Click += (sender, eventArgs) => Console.WriteLine("HELP I WAS CLICKED OMG");

Or with a function:

pictureBox.Click += PictureBox_Click;

....

private void PictureBox_Click(object sender, EventArgs e)
{
    Console.WriteLine("Stop clicking me >:(");
}

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