Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically programming a grid consisting of 64 buttons (8x8)

I'm trying to create a chess game purely for my learning C# and chess. Just to start off with, I would like to create an 8x8 grid of buttons through code rather than the designer. This would save me hard coding each button individually.

A button array would seem a good way to start but I have no idea how to implement this.

like image 775
Rg786 Avatar asked Oct 12 '11 12:10

Rg786


1 Answers

You can create a "square" class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;


class Square:PictureBox
{
   private bool color;
   private char piece;
}

and define an array to make place for 8x8 squares.

public partial class Form1 : Form
{
 Square[,] square = new Square[8, 8];

 public Form1()
 {
  InitializeComponent();
  int i, j;

  for (i = 0; i < 8; i++)
  {
     for (j = 0; j < 8; j++)
     {
       this.square[i, j] = new Square();//Creating the chess object//
       this.square[i, j].BackColor = System.Drawing.SystemColors.ActiveCaption;
       this.square[i, j].BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
       this.square[i, j].Location = new System.Drawing.Point(57 + i * 40, 109 + j * 40);
       this.square[i, j].Name = "chessBox1";
       this.square[i, j].Size = new System.Drawing.Size(40, 40);
       this.square[i, j].TabIndex = 2;
       this.square[i, j].TabStop = false;
       this.Controls.Add(this.square[i, j]);
     }
  }
 }
}
like image 164
Alon Adler Avatar answered Oct 16 '22 20:10

Alon Adler