Aidenn
Aidenn

Reputation: 559

Unable to create a new Label on a Windows Forms Application when clicking a button (C#)

I am trying to add a new label when clicking on a button. Shouldn't be too difficult but I just can't get it working :(

private void button3_Click(object sender, EventArgs e)
    {
        Label Label10 = new Label();
        Label10.Location = new Point(23, 100);
        Label10.Text = textBox1.Text;
        Parent.Controls.Add(Label10);
    }

I get an error when trying to debug it with a not too explicit message:

"NullReferenceException was unhandled."

Not sure to what it may be referring... I am using the "new" keyword to create the new instance, what may I be missing?

Thanks!

Upvotes: 0

Views: 121

Answers (2)

Daniel A. White
Daniel A. White

Reputation: 190907

Is Parent null? It could be on there too. You might just call this.Controls.Add(...).

Upvotes: 1

benjy
benjy

Reputation: 4716

textbox1 is probably what's throwing that exception. Can you step through your code in the debugger?

Upvotes: 0

Related Questions