How to create magic square like this picture in C# windows form? I already have
ID: 3776423 • Letter: H
Question
How to create magic square like this picture in C# windows form?
I already have a code in console program for this question but I dont know how to put it in Windows Form like picture. Also, show steps how to create like picture
This is my code:
static void Main(string[] args)
{
bool correctInput = false;
int n = 0;
while (!correctInput)
{
Console.WriteLine("Input an odd number:");
string input = Console.ReadLine();
if (!int.TryParse(input, out n))
{
Console.WriteLine("This is not a number '" + input + "'! Press any key to retry");
Console.ReadLine();
}
else if (Convert.ToInt16(input) % 2 == 0)
{
Console.WriteLine("This is not an odd number '" + input + "'! Press any key to retry");
Console.ReadLine();
}
else
{
n = Convert.ToInt16(input);
correctInput = true;
}
}
int nSquare = n * n;
int y = 0;
int x = (n / 2);
int[,] magicSquare = new int[n, n];
for (int a = 1; a <= nSquare; ++a)
{
magicSquare[y, x] = a;
y--;
x++;
if (a % n == 0)
{
y += 2;
x -= 1;
}
else
{
x = (x + n) % n;
y = (y + n) % n;
}
}
for (int a = 0; a < n; a++)
{
for (int b = 0; b < n; b++)
{
Console.Write(Convert.ToString(magicSquare[a, b]).PadLeft((Convert.ToString(nSquare).Length), ' ') + " ");
}
Console.WriteLine("");
}
}
8 6 3 5 7 4 9 2Explanation / Answer
Include this method in your program and call this program with size of magic squuare box you needed....
public void generateMagicSquare(int boxSize)
{
//refreshing form to erase previous data
foreach (Control tempItem in this.Controls)
{
this.Controls.Remove(tempItem);
tempItem.Dispose();
}
//creatting Table layout magicSquarePanel
var magicSquarePanel = new TableLayoutPanel();
magicSquarePanel.RowCount = boxSize;
magicSquarePanel.ColumnCount = boxSize;
magicSquarePanel.BackColor = Color.Black;
//generate rows and columns in panel
for (int i = 0; i < boxSize; i++)
{
var percentage = 100f / (float)boxSize;
magicSquarePanel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, percentage));
magicSquarePanel.RowStyles.Add(new RowStyle(SizeType.Percent, percentage));
}
// adding each buttons with our values
for (var i = 0; i < boxSize; i++)
{
for (var j = 0; j < boxSize; j++)
{
var myButton = new Button();
myButton.BackColor = Color.Lime;
myButton.Font = new Font(myButton.Font.FontFamily, 20, FontStyle.Bold);
myButton.FlatStyle = FlatStyle.Flat;
// adding button text
myButton.Text = string.Format("{0}", (i) * boxSize + j + 1);
myButton.Name = string.Format("Button{0}", myButton.Text);
myButton.Dock = DockStyle.Fill;
//if interaction need
myButton.Click += b_Click;
magicSquarePanel.Controls.Add(myButton, j, i);
}
}
magicSquarePanel.Dock = DockStyle.Fill;
this.Controls.Add(magicSquarePanel);
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.