C# 通过单击表单按钮更改在公共类中创建的标签
很难理解类以及为什么我无法访问某些对象。 我如何修改代码以便可以更改所有类/事件中的“地图”(这是一堆标签)属性?
Draw2d() 方法在主窗体上创建了几个标签,我希望在不同的事件上更改这些标签(在本例中单击按钮)。
有人可以帮助我,或者只是提示我正确的方向。
代码:
公共部分类Form1:表格
{
public void Draw2d()
{
const int spacing = 20;
Label[][] map = new Label[5][];
for (int x = 0; x < 5; x++)
{
map[x] = new Label[5];
for (int y = 0; y < 5; y++)
{
map[x][y] = new Label();
map[x][y].AutoSize = true;
map[x][y].Location = new System.Drawing.Point(x * spacing, y * spacing);
map[x][y].Name = "map" + x.ToString() + "," + y.ToString();
map[x][y].Size = new System.Drawing.Size(spacing, spacing);
map[x][y].TabIndex = 0;
map[x][y].Text = "0";
}
this.Controls.AddRange(map[x]);
}
}
public Form1()
{
InitializeComponent();
}
public void Form1_Load(object sender, EventArgs e)
{
Draw2d();
}
private void button1_Click(object sender, EventArgs e)
{
map[0][0].Text = "1"; // <-- Doesn't work
}
}
谢谢!
Having hard time understanding classes and why I can't access certain object.
How can i modify the code so I can change "map"(which is a bunch of labels) properties in all of my classes/events?
The method Draw2d() creates a couple of labels on the main form that I wish to change on different events(button click in this example).
Can someone help me, or just hint me into the right direction.
The Code:
public partial class Form1 : Form
{
public void Draw2d()
{
const int spacing = 20;
Label[][] map = new Label[5][];
for (int x = 0; x < 5; x++)
{
map[x] = new Label[5];
for (int y = 0; y < 5; y++)
{
map[x][y] = new Label();
map[x][y].AutoSize = true;
map[x][y].Location = new System.Drawing.Point(x * spacing, y * spacing);
map[x][y].Name = "map" + x.ToString() + "," + y.ToString();
map[x][y].Size = new System.Drawing.Size(spacing, spacing);
map[x][y].TabIndex = 0;
map[x][y].Text = "0";
}
this.Controls.AddRange(map[x]);
}
}
public Form1()
{
InitializeComponent();
}
public void Form1_Load(object sender, EventArgs e)
{
Draw2d();
}
private void button1_Click(object sender, EventArgs e)
{
map[0][0].Text = "1"; // <-- Doesn't work
}
}
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您必须将映射声明为属性(全局到类)
然后您可以在类内部使用
或从外部使用
you have to declare the map as property(global to class)
then you can use inside class like
or from outside like
我的猜测是您添加了
但忘记将 Draw2d 的第二行从 更改为
我
刚刚尝试了您的代码,如果您更改这两行,它就可以正常工作。如果这不是问题,您能说出您遇到的错误吗?
My guess is that you added
but forgot to change the second line of Draw2d from
to
I just tried your code, and it works fine if you change those two lines. If that's not the problem, could you say what error you're getting, please?