Create dynamic buttons in the grid - create a magic square user interface

I have to create a magic square in 2D using a Windows Forms application. It should look like this:

Image of a 3x3 magic square with the numbers shown and the grid.

However, the user should be able to determine the size of the square (3x3, 5x5, 7x7, etc.). I already wrote the code in the Console application, but I donโ€™t know how to add 2D graphics.

Someone already asked this question ( How do I put my result in a GUI? ), And one of the answers was to use a DataGridView , but I'm not sure what this is what I am looking for, since I cannot make it look like per image.

Any ideas or tips?

+6
source share
2 answers

You can use TableLayoutPanel and dynamically add buttons to the panel.

If you don't need button interaction, you can add a Label instead.

Create square dynamically:

 public void CreateSquare(int size) { //Remove previously created controls and free resources foreach (Control item in this.Controls) { this.Controls.Remove(item); item.Dispose(); } //Create TableLayoutPanel var panel = new TableLayoutPanel(); panel.RowCount = size; panel.ColumnCount = size; panel.BackColor = Color.Black; //Set the equal size for columns and rows for (int i = 0; i < size; i++) { var percent = 100f / (float)size; panel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, percent)); panel.RowStyles.Add(new RowStyle(SizeType.Percent, percent)); } //Add buttons, if you have your desired output in an array //you can set the text of buttons from your array for (var i = 0; i < size; i++) { for (var j = 0; j < size; j++) { var button = new Button(); button.BackColor = Color.Lime; button.Font = new Font(button.Font.FontFamily, 20, FontStyle.Bold); button.FlatStyle = FlatStyle.Flat; //you can set the text of buttons from your array //For example button.Text = array[i,j].ToString(); button.Text = string.Format("{0}", (i) * size + j + 1); button.Name = string.Format("Button{0}", button.Text); button.Dock = DockStyle.Fill; //If you need interaction with buttons button.Click += b_Click; panel.Controls.Add(button, j, i); } } panel.Dock = DockStyle.Fill; this.Controls.Add(panel); } 

If you need interaction with buttons

 void button_Click(object sender, EventArgs e) { var button = (Button)sender; //Instead put your logic here MessageBox.Show(string.Format("You clicked {0}", button.Text)); } 

For example, you can call

 CreateSquare(3); 

Screenshot:

enter image description here

+8
source

You can create a form and add a TableLayoutPanel with this property.

 tableLayoutPanel1.Dock = DockStyle.Fill; tableLayoutPanel1.BackColor = Color.Gold; 

and this is the result

enter image description here

When you create rows and columns to set the percentage correctly this way:

enter image description here

After that, you can add a button or shortcut to each square.

enter image description here

+3
source

Source: https://habr.com/ru/post/1236995/


All Articles