Background: I am coding for a puzzle game for my school Assignment. I have a puzzle game saved in a text file. Now I'm loading it to the form by reading from the text file saved. In the text file, the first two lines are total rows and columns of tiles (2d PictureBoxes) and the following lines are row number, column number, and image index of each PictureBox.
Approach: I am using a two-dimensional array of Tile (custom control class that inherits from PictureBox Class) references and using a nested loop to read each tile's (PictureBoxes') information ie. row number, column number, and image index. The tile class has properties named Row, Column, and TileType. I am trying to assign value to the property inside the nested loop.
//Tile Class
public class Tile : PictureBox
{
private int row;
private int column;
private int tileType;
public int Row{get; set;}
public int Column { get; set; }
public int TileType { get; set; }
}
public Tile[,] LoadPictureBoxes(string filename)
{
Tile[,] tile;
//Read the file
if (System.IO.File.Exists(filename) == true)
{
StreamReader load = new StreamReader(filename);
int nRow = int.Parse(load.ReadLine());
int nCol = int.Parse(load.ReadLine());
//declare two dimensional array of Tile Reference
tile = new Tile[nRow, nCol];
//using nested loop to read each tile's information
for(int i=0; i < nRow; i++)
{
for(int j=0; j < nCol; j++)
{
tile[i, j].Row = int.Parse(load.ReadLine()); //gets an exception here
tile[i, j].Column = int.Parse(load.ReadLine()); //gets an exception here
tile[i, j].TileType = int.Parse(load.ReadLine()); //gets an exception here
}
}
load.Close();
return tile;
}
return new Tile[0, 0];
}
private void loadToolStripMenuItem_Click(object sender, EventArgs e)
{
DialogResult r = dlgLoad.ShowDialog();
switch (r)
{
case DialogResult.Cancel:
break;
case DialogResult.OK:
string fileName = dlgLoad.FileName;
Tile[,] tile = LoadPictureBoxes(fileName);
int leftPos = 100;
int topPos = 0;
int height = 100;
int width = 100;
int rowCount = 0;
int columnCount = 0;
//loop after each row of picturebox is generated
for (int rowNumber = 0; rowNumber < tile.GetLength(0); ++rowNumber)
{
++rowCount;
for (int colNumber = 0; colNumber < tile.GetLength(1); ++colNumber)
{
++columnCount;
Tile pic = new Tile();
pic.Left = leftPos;
pic.Top = topPos;
pic.Height = height;
pic.Width = width;
pic.BorderStyle = BorderStyle.Fixed3D;
pic.SizeMode = PictureBoxSizeMode.StretchImage;
tile[rowCount, columnCount] = pic;
pnlLoadGame.Controls.Add(pic);
leftPos += width;
}
topPos += height;
}
pnlLoadGame.Size = new Size(100 * rowCount, 100 * columnCount);
pnlGameScore.Left = 100 + 100 * columnCount;
break;
}
}
Problem: I get an exception at runtime: System.NullReferenceException: 'Object reference not set to an instance of an object.' Is there an alternative way to assign value to the property of custom PictureBox?