In this example, I’ll show you How to create a chess board using Windows Form App.
C# Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 | using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace ChessBoard { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private Panel[,] _chessBoardPanels; private void Form1_Load(object sender, EventArgs e) { const int tileSize = 80; const int gridSize = 8; var clr1 = Color.Black; var clr2 = Color.White; this.Width = 658; this.Height = 680; this.Text = "csharp-console-examples.com"; // initialize the "chess board" _chessBoardPanels = new Panel[gridSize, gridSize]; // double for loop to handle all rows and columns for (var n = 0; n < 8; n++) { for (var m = 0; m < 8; m++) { // create new Panel control which will be one // chess board tile var newPanel = new Panel { Size = new Size(tileSize, tileSize), Location = new Point(tileSize * n, tileSize * m) }; // add to Form's Controls so that they show up Controls.Add(newPanel); // add to our 2d array of panels for future use _chessBoardPanels[n, m] = newPanel; // color the backgrounds if ((n + m) % 2 == 0) { newPanel.BackColor = clr1; } else { newPanel.BackColor = clr2; } } } } } } |
Output: