在网格布局中创建动态按钮 - 创建幻方 UI [英] Create dynamic buttons in a grid layout - Create a magic square UI

查看:20
本文介绍了在网格布局中创建动态按钮 - 创建幻方 UI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我应该使用 Windows 窗体应用程序在 2D 中创建一个幻方.它应该是这样的:

但是,用户应该能够决定正方形的大小(3x3、5x5、7x7 等).我已经在控制台应用程序中编写了代码,但我不知道如何添加二维图形.

有人已经问过这个问题了(

I'm supposed to create a magic square in 2D using Windows Forms Application. It should look like this:

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

Somebody already asked this question (How do I put my result into a GUI?), and one of the answers was to use DataGridView, but I'm not sure if that's what I'm looking for, since I can't make it look like the picture.

Any ideas or advice?

解决方案

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

If you don't need interaction with buttons, you can add 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));
}

As an example, you can call

CreateSquare(3);

Screenshot:

这篇关于在网格布局中创建动态按钮 - 创建幻方 UI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆