I am attempting to solve an exercise from a book. (with no published answer)
I need to reference a PictureBox object which is present on my form to an Object Array. (I need to assign four of them really)
I initialise the array and assign the variables to it. I then call a method within each item in the array however the PictureBox object is not assigned. (Null Exception)
I’m a little baffled as I’ve found snippets of code publicly on the net which show I’m doing this correctly.
Code Below for pointers please:
Main Class
public partial class Form1 : Form
{
Greyhound[] greyhoundArray = new Greyhound[4];
public Form1()
{
greyhoundArray[0] = new Greyhound() { Location = 0, MyPictureBox = dog1, RaceTrackLenght = 100, StartingPosition = 0 };
greyhoundArray[1] = new Greyhound() { Location = 0, MyPictureBox = dog2, RaceTrackLenght = 100, StartingPosition = 0 };
greyhoundArray[2] = new Greyhound() { Location = 0, MyPictureBox = dog3, RaceTrackLenght = 100, StartingPosition = 0 };
greyhoundArray[3] = new Greyhound() { Location = 0, MyPictureBox = dog4, RaceTrackLenght = 100, StartingPosition = 0 };
InitializeComponent();
}
private void timer1_Tick(object sender, EventArgs e)
{
foreach (Greyhound greyhound in greyhoundArray)
{
greyhound.Run();
}
}
}
Greyhound Class
public class Greyhound
{
public int StartingPosition;
public int RaceTrackLenght;
public PictureBox MyPictureBox;
public int Location = 0;
public Random Randomiser;
public void Run()
{
// MessageBox.Show(MyPictureBox.Name + " was called");
Randomiser = new Random();
int distance = Randomiser.Next(0, 4);
Point p = MyPictureBox.Location;
p.X += distance;
MyPictureBox.Location = p;
}
public void TakeStartingPosition()
{ }
}
Also I can confirm each dog PictureBox does exist on the form:
snippet from Form1.Designer.cs
//
// dog1
//
this.dog1.Image = ((System.Drawing.Image)(resources.GetObject("dog1.Image")));
this.dog1.Location = new System.Drawing.Point(17, 21);
this.dog1.Name = "dog1";
this.dog1.Size = new System.Drawing.Size(71, 26);
this.dog1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.CenterImage;
this.dog1.TabIndex = 2;
this.dog1.TabStop = false;
Place the call to
InitializeComponent()before the initialization of GreyHound array.When you call the initialization of the Greyhound array, you have not called yet the
this.dog1 = new PictureBox()inside InitializeComponent, so you copy a null into theMyPictureBoxproperty of each Greyhound instancesAlso, I think you have a problem with the Randomiser variable in your Greyhound class