Search code examples
c#panel

Add label to Panel programmatically


So I have a form, and I want to add some Panels with some controls(labels, and radiobuttons) when the form loads.
And I want to do it from the code, of course(it's for making an application with tests, and the questions will be random)
This is what I have done till now:

List<Panel>ls=new List<Panel>();

private void VizualizareTest_Load(object sender, EventArgs e)
{
    for (int i = 0; i < 4; i++)
    {
        Panel pan = new Panel();
        pan.Name = "panel" + i;
        ls.Add(pan);
        Label l = new Label();
        l.Text = "l"+i;
        pan.Controls.Add(l);
        pan.Show();
    }

}

But it doesn't show anything on the form.


Solution

  • Add the panel just created to the Form.Controls collection

    private void VizualizareTest_Load(object sender, EventArgs e)
    {
        for (int i = 0; i < 4; i++)
        {
            Panel pan = new Panel();
            pan.Name = "panel" + i;
            ls.Add(pan);
            Label l = new Label();
            l.Text = "l"+i;
            pan.Location = new Point(10, i * 100);
            pan.Size = new Size(200, 90);  // just an example
            pan.Controls.Add(l);
            this.Controls.Add(pan);
    
        }
    }