1

Hi People I'm newbie in the C# world and I'm having a problem. I have done an array in the Form_Load method of my program, but I need to access the array in a picture_box method like this:

        private void Form2_Load(object sender, EventArgs e)
    {
        //In this method we get a random array to set the images

        int[] imgArray = new int[20];

        Random aleatorio = new Random();

        int num, contador = 0;

        num = aleatorio.Next(1, 21);

        imgArray[contador] = num;
        contador++;

        while (contador < 20)
        {
            num = aleatorio.Next(1, 21);
            for (int i = 0; i <= contador; i++)
            {
                if (num == imgArray[i])
                {
                    i = contador;
                }
                else
                {
                    if (i + 1 == contador)
                    {
                        imgArray[contador] = num;
                        contador++;
                        i = contador;
                    }
                }
            }
        }

    }


    private void pictureBox1_Click(object sender, EventArgs e)
    {
        pictureBox1.Image = Image.FromFile(@"C:\Users\UserName\Desktop\MyMemoryGame\" + imgArray[0] + ".jpg");
    }

But I only get the error: Error 1 The name 'imgArray' does not exist in the current context

Andres
  • 351
  • 1
  • 4
  • 11

2 Answers2

5

You need to define int[] imgArray at the class level (outside of Form2_Load) rather than inside it. Otherwise the "scope" of that variable is limited to that function. You will need to knock off the first "int[]" part in Form2_Load to prevent you from just declaring a new variable.

For example:

public class MyClass
{ 
    private int[] myInt;

    public void Form2_Load(...) {
        myInt = ...;
    }

}
Rich
  • 3,640
  • 3
  • 20
  • 24
  • Thank you just one thing it wasn't necessary to declare my array as private at least in my case. Again thanks a lot! – Andres Jun 05 '11 at 07:15
3

The error means exactly what it says.

You've declared the array in the scope of the Form2_Load function. Outside of it, it will not exist.

To do what you're trying to achieve, add a private array to the form itself.

private int[] _imgArray = new int[20];

private void Form2_Load(object sender, EventArgs e)
{
    //Setup the imgArray
}

private void pictureBox1_Click(object sender, EventArgs e)
{
    //_imgArray is now available as its scope is to the class, not just the Form2_Load method

}

Hopefully that helps.

Khepri
  • 9,547
  • 5
  • 45
  • 61