3

I added a panel to Form1 component. That panel is named panel1.

When browsing a generic list, I want to add labels dynamically. Look to my little code:

if (list.Count > 0)
{

    foreach (TLClass item in list)
    {
        Label key = new Label();
        key.Text = item.Key;
        panel1.Container.Add(key);  //here throws an exception

        Label code = new Label();
        code.Text = item.Code.ToString();
        panel1.Container.Add(code);

        Label en = new Label();
        en.Text = item.Languages["EN-EN"].ToString();
        panel1.Container.Add(en);


        Label fr = new Label();
        fr.Text = item.Languages["FR-FR"].ToString();
        panel1.Container.Add(fr);

        Label nl = new Label();
        nl.Text = item.Languages["NL-NL"].ToString();
        panel1.Container.Add(nl);

        Label ro = new Label();
        ro.Text = item.Languages["RO-RO"].ToString();
        panel1.Container.Add(ro);

        Form1.ActiveForm.Container.Add(panel1);
    }
}

After line panel1.Container.Add(key);, immediately throws an exception NullReferenceException.

Why ? Where's my mistake ?

enter image description here

Problem solved I called with Controls instead of Container

Jonny
  • 1,413
  • 16
  • 23
Snake Eyes
  • 14,643
  • 31
  • 97
  • 188

1 Answers1

4

You add controls to the container.
Which should be the parent form, but when you Add the parent form is not set.
However the right way is to add to the controls collection of the panel

panel1.Controls.Add(key);
Steve
  • 203,265
  • 19
  • 210
  • 265