在 C# 中的正方形 for 循环中在运行时添加复选框

Add CheckBoxes on runtime in a square for loop in C#

我想在 x*y 矩阵中动态添加复选框。 我想到的启动 for 循环的最简单方法是 O(n²)。 我有 2 个文本框,用于矩阵的宽度和高度。 在我的示例中,我做了 10x10;当我按下按钮时,它只会创建 1 个复选框。 我首先尝试直接将复选框添加到面板,但我以某种方式得到了 NullReferenceException。现在我在一个列表中,它填充了 for 循环,然后在 foreach 循环中被读出。

如有任何帮助,我们将不胜感激。

提前致谢

m0ddixx

我的尝试:

namespace LED_Matrix_Control
{
public partial class Form1 : Form
{
    private LedMatrix ledMatrix;
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        int width= Convert.ToInt32(breiteFeld.Text);
        int height = Convert.ToInt32(hoeheFeld.Text);
        List<CheckBox> ledchecks = new List<CheckBox>();
        ledMatrix = new LedMatrix(breite, hoehe);
        for(int x = 0; x < breite; x++)
        {
            for(int y = 0; y < hoehe; y++)
            {
                ledchecks.Add(addCheckBox(x, y));
            }
        }
        foreach(CheckBox finalLedChk in ledchecks)
        {
            panel1.Controls.Add(finalLedChk);
        }
    }
    private CheckBox addCheckBox(int x, int y)
    {
        CheckBox ledcheck = new CheckBox();
        ledcheck.Location = new Point(x, y);
        return ledcheck;
    }
}
}

如果您的面板足够大以容纳所有控件,那么您的问题就很简单了。您将所有创建的复选框大致堆叠在同一位置。

复选框可能是最小的控件(连同单选按钮),但尽管如此,它们还是有尺寸的,如果您想看到它们,您应该将它们放在足够不同的位置

您的代码不需要两个循环。你可以这样写

    for(int x = 0; x < breite; x++)
    {
        for(int y = 0; y < hoehe; y++)
        {
            CheckBox ledcheck = new CheckBox();
            ledcheck.Location = new Point(x * 20, y * 20);
            ledcheck.Size = new Size(15,15);
            panel1.Controls.Add(ledcheck);
        }
    }

还可以考虑探索 TableLayoutPanel 的使用。此控件提供某种形式的网格来帮助您自动定位复选框。

例如

Form f = new Form();
TableLayoutPanel tlp = new TableLayoutPanel();
tlp.RowCount = 5;  // <= this should come from user input 
tlp.ColumnCount = 5; // <= this should come from user input 

tlp.Dock = DockStyle.Fill;

for (int x = 0; x < 5; x++)
{
    for (int y = 0; y < 5; y++)
    {
        CheckBox ledcheck = new CheckBox();
        // No need to position the checkboxes.....
        // ledcheck.Location = new Point(x * 20, y * 20);
        ledcheck.Size = new Size(15,15);
        tlp.Controls.Add(ledcheck);
    }
}
f.Controls.Add(tlp);
f.Show();