c# .net winforms 2d

c# - Crear botones dinámicos en un diseño de cuadrícula: cree una IU cuadrada mágica



.net winforms (2)

Se supone que debo crear un cuadrado mágico en 2D con la aplicación de formularios Windows Forms. Debe tener un aspecto como este:

Sin embargo, el usuario debe poder decidir el tamaño del cuadrado (3x3, 5x5, 7x7, etc.). Ya escribí el código en una aplicación de consola, pero no sé cómo agregar los gráficos 2D.

Alguien ya hizo esta pregunta ( ¿Cómo pongo mi resultado en una GUI? ), Y una de las respuestas fue usar DataGridView , pero no estoy seguro de si eso es lo que estoy buscando, ya que no puedo hacerlo Se parece a la imagen.

¿Alguna idea o consejo?


Puede crear un formulario y agregar un TableLayoutPanel con esta propiedad

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

Y este es el resultado

Cuando crea Fila y Columna, para ajustar correctamente el porcentaje de esta manera:

Después de esto, puede agregar un Botón o Etiqueta en cada cuadrado.


Puede usar un TableLayoutPanel y agregar botones al panel dinámicamente.

Si no necesita interacción con los botones, puede agregar Label lugar.

Crear cuadrado dinámicamente:

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); }

Si necesitas interacción con botones

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)); }

Como ejemplo, puedes llamar

CreateSquare(3);

Captura de pantalla: