0

I want to create an array of picturebox names, which I will later use in a FOREACH loop and do a certain thing to each picturebox instead of having to write the code for all of the pictureboxes separately. In another solution the code below worked, but here it only returns an error: "A field initializer cannot reference the non-static field, method, or property 'Puzzle.Form1.pic1'"

I could not find what I was looking for on the internet, even though I tried to write it in different ways. Thanks!

    //Define an array and place the 9 picture boxes in it

    //System.Drawing. [] PictureBox = {}
    //PictureBox[] Pictures1 = new PictureBox[9];
    //PictureBox[] Pictures1 = { pic1, pic2 };
    //PictureBox pBoxes = new PictureBox[] {pic1, pic2, pic3};

    PictureBox[] diceloc = { pic1, pic2, pic3, pic4, pic5, pic6, pic7, pic8, pic9 };
3
  • do you use this code inside a static method??? Commented Jun 24, 2015 at 9:54
  • 2
    You have to study very basics of C# first, before asking any further question (looking at your attempts). Commented Jun 24, 2015 at 9:59
  • There is not much you (or any newbie) can or should do with the names, which are basically strings. You need to use references! Commented Jun 24, 2015 at 10:40

1 Answer 1

2

You need to create a new instance of the PictureBox class before you can set its values.

PictureBox[] diceloc = new PictureBox[] {pic1, pic2, pic3, pic4};
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! It still didn't work, but then I moved the whole code to within "public Form1()" instead of "public partial class Form1 : Form" and it's working

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.