Home > DeveloperSection > Forums > Pass array from form load to button click
ezra heywood
ezra heywood

Total Post:145

Points:1019
Posted on    November-14-2014 10:45 PM

 C# .NET 
Ratings:


 1 Reply(s)
 581  View(s)
Rate this:

New C# user. I understand global variables are not part of C#. Been trying learning properties, set and get. But I have what must be a common situation and I can't find the answer. This is what normally seems to happen when I design a form:

private void Form1_Load(object sender, EventArgs e) {        

 

    private void Form1_Load(object sender, EventArgs e)

        {

         Label[]  labelsArray = { label1, label2, label3, label4, label5 };

        }

    private void button1_Click(object sender, EventArgs e)

        {

            ...

        }

}

So I made a "labelsArray" in Form1_Load that I want to use in the button1_Click. But I cannot - "Error 1 The name 'labelsArray' does not exist in the current context".

I do have access to the labels in button1_Click and I suppose I can re-declare the array and it'd work. But seems like I should be able to pass the array from Form1_Load to button1_Click and use it. But I'm lost after trying many things. How is it done please?



Kamlakar Singh
Kamlakar Singh

Total Post:28

Points:196
Posted on    November-15-2014 3:16 AM

All you need to do is to declare the variable outside the methods like:

private Label[]  labelsArray = null;

private void Form1_Load(object sender, EventArgs e){

   labelsArray = new Label[]{ label1, label2, label3, label4, label5 };

}

private void button1_Click(object sender, EventArgs e){}


Don't want to miss updates? Please click the below button!

Follow MindStick