Areeb Raza
Areeb Raza

Reputation: 9

Instantiate object of a class under form class

I am new to windows forms. I am trying to instantiate a object of a public class and calling a method drawBoard() when button1 is pressed. Method drawBoard() through which I want to set the properties of pictureBox2. But the code didn't work.

  public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();                                                                   
        }

        public class gameBoard :Form1
        {
            public void drawBoard()
            {
                pictureBox2.ImageLocation = @"E:\My Data\DoCx\CS\3rd Sem\OOP\proj\images\a.png";
                pictureBox2.SizeMode = PictureBoxSizeMode.Zoom;                      
            }            
        }

        private void button1_Click(object sender, EventArgs e)
        {             
            gameBoard a = new gameBoard();
            a.drawBoard();               
        }      
}

Also tried to implement this in other two ways:

 public partial class Form1 : Form
    {
 public Form1()
        {
            InitializeComponent();

            pictureBox2.ImageLocation = @"E:\My Data\DoCx\CS\3rd Sem\OOP\proj\images\a.png";
            pictureBox2.SizeMode = PictureBoxSizeMode.Zoom;
            pictureBox2.BackColor = Color.Transparent;                               
        }    
 }

and

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();         
        }

        private void button1_Click(object sender, EventArgs e)
        {            
            pictureBox2.ImageLocation = @"E:\My Data\DoCx\CS\3rd Sem\OOP\proj\images\a.png";
            pictureBox2.SizeMode = PictureBoxSizeMode.Zoom;   
        }
    }

Both worked. Directly loads the image when the code runs. And also when the button1 pressed in second way. I wonder how to call the pictureBox properties when they defined in a method of a user-defined class.

Upvotes: 0

Views: 86

Answers (1)

Rahul
Rahul

Reputation: 77866

If you observe carefully then your gameBoard is defined as a nested class inside Form1 and it also inherits from Form control, which doesn't make sense. You probably wan to have the class defined outside like (probably in a separate file)

    public class gameBoard
    {
        private PictureBox _box;
        public gameBoard(PictureBox box)
        {
            _box = box;
        }
        public void drawBoard()
        {
            _box.ImageLocation = @"E:\My Data\DoCx\CS\3rd Sem\OOP\proj\images\a.png";
            _box.SizeMode = PictureBoxSizeMode.Zoom;                      
        }            
    }

Upvotes: 4

Related Questions