我尝试将0到11的文本放在12个具有球形图像的图片框上,但将所有文本都设为11。
如何获得0到11之间的文字?
这是我的代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace wfballs2
{
public partial class Form1 : Form
{
String s;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
PictureBox[] Shapes = new PictureBox[12];
for (int i = 0; i < 12; i++)
{
s = Convert.ToString(i);
Shapes[i] = new PictureBox();
Shapes[i].Name = "ball" + i.ToString();
Shapes[i].Location = new Point(10 + 45 * i, 300);
Shapes[i].Size = new Size(40, 40);
Shapes[i].Image = Image.FromFile(@ "C:\Users\Eiko\Desktop\ball\ball.jpg");
Shapes[i].SizeMode = PictureBoxSizeMode.CenterImage;
Shapes[i].Visible = true;
this.Controls.Add(Shapes[i]);
Shapes[i].Paint += new PaintEventHandler((sender2, e2) =>
{
e2.Graphics.DrawString(s, Font, Brushes.Black, 10, 13);
});
}
}
}
}
变量s
是表单中的一个实例,因此它的值由表单和您创建的所有形状共享。
每次绘制您的形状之一时,此代码:
e2.Graphics.DrawString(s, Font, Brushes.Black, 10, 13);
会跑。那s
是您Form的一个实例变量。它将显示所有形状的最后设置值。在您的情况下,这发生在for循环的最后一次迭代中,因此发生在11。
要解决此问题,您必须在匿名Convert.ToString(val)
事件处理程序之前捕获局部变量中的循环变量,然后使用该局部变量在事件处理程序中执行操作,如下所示:
var val = i; // capture variable
Shapes[i].Paint += new PaintEventHandler((sender2, e2) =>
{
// use captured variable here
e2.Graphics.DrawString(Convert.ToString(val), Font, Brushes.Black, 10, 13);
});
这将生成带有基于的局部变量的字符串val
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句