jeudi 17 novembre 2016

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




Aucun commentaire:

Enregistrer un commentaire