m0ddixx m0ddixx - 23 days ago 6
C# Question

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

I want to dynamically add Checkboxes in a x*y matrix.
The simplest way that came to my mind to start a for loop which goes by O(n²).
I have 2 TextBoxes which are for the width and height of the matrix.
In my example i did 10x10; When i press the button it just creates 1 Checkbox.
I first tried to directly add the Checkbox to the panel but i somehow got a NullReferenceException. Now i am on a List which fills in the for loop and gets read out afterwards in the foreach loop.

Any help would be appreciated.

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

Answer

If you panel is big enough to host all controls then you have just a simple problem. You are stacking all the created checkboxes roughly at the same location.

The checkbox is probably the smallest control (together with the radiobutton) but notwistanding this they have a size and if you want to see them you should position them in different enough location

You code don't requires two loops. You could write something like this

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

Consider also to explore the use of a TableLayoutPanel. This control provides some form of grid to help you to automatically position your checkboxes.