[英]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.
图像渲染正常,但我不知道如何创建 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 >:(");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.