开发者

C# change labels created in public class from form button click

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!


you have to declare the map as property(global to class)

public partial class Form1 : Form {
   public Label[][] map;
   ....
}

then you can use inside class like

this->map[...][...]

or from outside like

objClass->map[...][...]


My guess is that you added

public Label[][] map;

but forgot to change the second line of Draw2d from

Label[][] map = new Label[5][];

to

map = new Label[5][];

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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜