I am experimenting and learning C# by coding the game of LIFE. Currently I have a pictureBox and a function drawGrid that creates a grid overlay. In order to click in each cell inside the pictureBox I have implemented the property pictureBox1_MouseClick in which there is an if decision logic to know if a cell is selected or not. The issues I am running into comes when i click the squares quickly i get an Error: System.IndexOutOfRangeException which points to fill_in[x, y] = !fill_in[x, y];.
How can I increase the clicking accuracy of the pictureBox1_MouseClick event so I dont get that error?
Specific error:
`An unhandled exception of type ‘System.IndexOutOfRangeException’ occurred in life.exe
Additional information: Index was outside the bounds of the array.`
Code
namespace life
{
public partial class Form1 : Form
{
Graphics paper;
bool[,] fill_in = new bool[450, 450];
int cellSize = 10;
private void drawGrid()
{
int numOfCells = 100;
Pen p = new Pen(Color.Blue);
paper.Clear(Color.White);
for (int i = 0; i < numOfCells; i++)
{
// Vertical Lines
paper.DrawLine(p, i * cellSize, 0, i * cellSize, numOfCells * cellSize);
// Horizontal Lines
paper.DrawLine(p, 0, i * cellSize, numOfCells * cellSize, i * cellSize);
}
}
private void pictureBox1_MouseClick(object sender, MouseEventArgs e)
{
int x = cellSize * (e.X / cellSize);
int y = cellSize * (e.Y / cellSize);
// Reverse the value of fill_in[i, j] - if it was false, change to true,
// and if true change to false
fill_in[x, y] = !fill_in[x, y];
if (fill_in[x, y])
{
// Fill grid square with the filled color
paper.FillRectangle(Brushes.Red, x, y, 10, 10);
}
else
{
// Fill grid square with unfilled color
paper.FillRectangle(Brushes.White, x, y, 10, 10);
}
}
}
}
Please make sure your calculations return desired values:
In this scenario x and y can be outside the boundaries of your array. Example: cellsize * (450 / cellsize) equals 450 and this causes the error since allowed indices range from 0 to 449.
EDIT:
To fix this problem (and this is a really dirty and temporary fix), please change your code as follows:
More desirable and actually a lot smarter solution would be simply to adjust your table’s size to be exactly the same as the range of e.X and e.Y.
Hope this helps,
Piotr