I've been working on drawing a grid in C#, which works! But somehow I keep running into some problems with the method DrawGrid. I found that it is being redrawn every time a label gets added, and continuously after that. Here is my code:
Rectangle[,] rec = new Rectangle[6,6];
Label label_1 = new Label();
Label label_2 = new Label();
public Reversi()
{
ClientSize = new Size(500,425);
BackColor = Color.DarkGreen;
NewGame();
Paint += DrawGrid;
}
public void NewGame()
{
// here is some more stuff which I will leave out for the sake of clarity
for (int i = 0; i < grspel; i++)
{
for (int j = 0; j < grspel; j++)
{
rec[i, j] = new Rectangle(50 + i * 50, 100 + j * 50, 50, 50);
}
}
DrawLabels();
}
public void DrawLabels()
{
label_1.Location = new Point(20, 50);
label_1.Text = "Zwart: " + zwart;
Controls.Add(label_1);
label_2.Location = new Point(330, 50);
label_2.Text = "Wit: " + wit;
Controls.Add(label_2);
}
public void DrawGrid(object o, PaintEventArgs pea)
{
MessageBox.Show("test");
for (int i = 0; i < 6; i++)
{
for (int j = 0; j < 6; j++)
{
pea.Graphics.DrawRectangle(new Pen(Brushes.Black), rec[i,j]);
}
}
}
To visualize my problem I placed MessageBox.Show("test");
at the start of my DrawGrid method. The rest of my code (which is not on here) uses this method and is not working properly. I've narrowed the problem down to this.
Getting rid of the Controls.Add(label_i)
fixes the problem, but I need the labels.
Why does this happen and more importantly, how can I fix it?