PASS ARRAY FROM FORM LOAD TO BUTTON CLICK

ezra heywood

Total Post:145

Points:1019
Posted by  ezra heywood
.NET 
C#
 893  View(s)
Ratings:
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?

  1. Mark M

    Post:28

    Points:196
    Re: Pass array from form load to button click

    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){}

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!