在c#的for循环中在运行时添加复选框

本文关键字:运行时 添加 复选框 循环 for | 更新日期: 2023-09-27 18:18:22

我想在x*y矩阵中动态添加复选框。我想到的最简单的开始for循环的方法是O(n²)。我有2个文本框,这是为矩阵的宽度和高度。在我的例子中,我是10x10;当我按下按钮,它只是创建1复选框。我第一次尝试直接将复选框添加到面板,但我不知何故得到了NullReferenceException。现在我在一个列表中,它填充在for循环中,然后在foreach循环中读取。

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

Thanks in advance

m0ddixx

My Try on this:

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

在c#的for循环中在运行时添加复选框

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

复选框可能是最小的控件(与单选按钮一起),但不是扭曲,它们有一个大小,如果你想看到它们,你应该将它们放置在不同的位置

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

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