What is the best way to create chess board using Windows Forms?
I am still new to graphics coding in winforms and I am not sure, which control to use for that?
There are a lot of ways. Here's an alternative that gets you started with some WinForms concepts:
(It uses a 2D grid of Panel controls to create a chessboard. To extend it you might change the background picture of each Panel to show chess pieces. The game play is up to you to define.)
// class member array of Panels to track chessboard tiles
private Panel[,] _chessBoardPanels;
// event handler of Form Load... init things here
private void Form_Load(object sender, EventArgs e)
{
const int tileSize = 40;
const int gridSize = 12;
var clr1 = Color.DarkGray;
var clr2 = Color.White;
// initialize the "chess board"
_chessBoardPanels = new Panel[gridSize, gridSize];
// double for loop to handle all rows and columns
for (var n = 0; n < gridSize; n++)
{
for (var m = 0; m < gridSize; 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 % 2 == 0)
newPanel.BackColor = m % 2 != 0 ? clr1 : clr2;
else
newPanel.BackColor = m % 2 != 0 ? clr2 : clr1;
}
}
}
In the controls OnPaint eventhandler, you start out by drawing the chessboard pattern either implicitly using the formula (floor(x * 8) mod 2) = (floor(y * 8) mod 2) or by just drawing the squares with Graphics.FillRectangle. The second step would be to draw the pieces on top with Graphics.DrawImage.
I don't know what you want to do with this chess board, but if it's only a background to display after pieces, your best shot is to set a background image.
Best way is to use a 'chess starter kit': http://www.chessbin.com/page/Chess-Game-Starer-Kit.aspx (alternative project: http://www.codeproject.com/KB/game/SrcChess.aspx)
Nowadays a lot of things have starter kits (for C#) which gives you a sample to get started on.