Snake Eyes
Snake Eyes

Reputation: 16764

NullReferenceException occurs when adding new labels in panel

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

Upvotes: 3

Views: 2092

Answers (1)

Steve
Steve

Reputation: 216323

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

Upvotes: 4

Related Questions