3

I have following code

   namespace Spaceship_Invaders
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
                Image myImage = Image.FromFile("image/Untitled.png");
                pictureBox1.Image = myImage;
            }

            public class spaceship { 
                Image myimage = Image.FromFile("image/Untitled6.png");
                Form1 myform = new Form1();
                 myform.pictureBox1.Image = myimage;            


            }

        }
    }

I have a picturebox in the form and I want to access the picturebox from the class spaceship but i can not access it. How to do this?

Alberto De Caro
  • 5,147
  • 9
  • 47
  • 73
asdfkjasdfjk
  • 3,784
  • 18
  • 64
  • 104
  • 1
    Before post a question, please do your homework. It is a basic issue in [oop](http://en.wikipedia.org/wiki/Object-oriented_programming). – Alberto De Caro Mar 29 '13 at 10:16

2 Answers2

2

[EDITED] You can access it this way:

public class spaceship
{ 
    Image myimage = Image.FromFile("image/Untitled6.png");
    Form1 myform = new Form1();

    spaceship()
    {
        myform.pictureBox1.Image = myimage;             
    }
}

Have a look here

Hossein Narimani Rad
  • 31,361
  • 18
  • 86
  • 116
  • Thanks, it works perfect now. May I ask you why spaceship() is necessary to access picturebox? Why can't I access it directly form the spaceship class? – asdfkjasdfjk Mar 29 '13 at 10:19
  • Of cource you can. `spaceship()` is a special method of the `spaceship` class named **Constructor**. In the class body you can only declare class members (also initialize them). In order to set their values you should use methods. – Hossein Narimani Rad Mar 29 '13 at 10:22
0

Rather than unsing a public field create a public property From1.TheImage to set the image to the PictureBox.

This allows you to implement checks, cross thread security if needed and to exchange the PictureBox with something else without changing your SpaceShip class.

Read this post: SO public fields/properties to get and idea about the risks of making fields public.

    public partial class Form1 : Form
    {

        public Image MyImage
        {
            get { return pictureBox1.Image; }
            set { 
                  //do some checks if neccessary
                  pictureBox1.Image = value; 
                }
        }

        public Form1()
        {
            InitializeComponent();
        }
    }
Community
  • 1
  • 1
  • There is plenty of documentation about C# around the web. But i will give a short example above. –  Mar 29 '13 at 10:26