views:

347

answers:

2

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!

+2  A: 

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[...][...]
Pentium10
The public label did the trick for Visual Studio, but I still can't figure out how to access the variable array map[][].map[1][1].Text = "1"; compiles but doesnät work.objClass->map[][] ? I don't understand that
Qrew
+1  A: 

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?

Matt Bishop
Matt : Thanks, it's working. It was my misstake. Thanks again! You have saved me alot of trouble :)
Qrew