如何在 C# 中编写动态图片框单击事件
本文关键字:单击 事件 动态 | 更新日期: 2023-09-27 18:32:27
private void button1_Click(object sender, EventArgs e)
{
PictureBox dynamicPicture1 = new PictureBox();
dynamicPicture1.Tag = i;
dynamicPicture1.Location = new Point(x, y);
dynamicPicture1.Name = "pictureBox" + i;
dynamicPicture1.Size = new System.Drawing.Size(30, 27);
dynamicPicture1.ImageLocation =
"C:''Users''Newfolder''Downloads''x`enter code here`ryrvc.jpg";
panel1.Controls.Add(dynamicPicture1);
}
试试这个更新的代码。
private void button1_Click(object sender, EventArgs e)
{
int s = 4;
int x = 0;
int y = 0;
for (int i = 0; i < s; i++)
{
if (i == 0)
{
x = 38;
y = 60;
}
else
{
y += 50;
}
PictureBox dynamicPicture1 = new PictureBox();
dynamicPicture1.Tag = i;
dynamicPicture1.Location = new Point(x, y);
dynamicPicture1.Name = "pictureBox" + i;
dynamicPicture1.Size = new System.Drawing.Size(30, 27);
dynamicPicture1.ImageLocation = @"C:'Users'nxa00960'Downloads'abc.jpg";
panel1.Controls.Add(dynamicPicture1);
dynamicPicture1.Click += dynamicPicture1_Click;
}
}
void dynamicPicture1_Click(object sender, EventArgs e)
{
var pictureBox = sender as PictureBox;
switch (pictureBox.Name)
{
case "pictureBox0":
//do something
break;
case "pictureBox1":
//do something
break;
case "pictureBox2":
//do something
break;
case "pictureBox3":
//do something
break;
default:
break;
}
}
你应该把你的event handler
Method
名称:
dynamicPicture1.Click += dynamicPicture1_Click; //note the name here
并在某处定义事件处理程序:
void dynamicPicture1_Click(object sender, EventArgs e) {
throw new NotImplementedException(); //default not implemented
}
事件处理程序的名称必须相互匹配...