0

I have a class in the same file as the Form1 : Form class (directly proceeding) and would like to create a new control (label thisObj = new label();) from within the class. I tried to use the following code:

Form1 form = new Form1(); label thisObj = new label(); thisObj.Name = "One"; form.Controls.Add(thisObj); 

However, when I do this, the form window doesn't load when starting the debugging.

EDIT: The line "Form1 form = new Form1()" causes the form not to load.

1
  • Form1 form = new Form1() doesn't load the form. You at least need to call Show or ShowDialog for that to happen. Commented Feb 13, 2012 at 18:59

3 Answers 3

2

Try with:

this.Controls.Add(thisObj); 

It will add the control to the current form.

Sign up to request clarification or add additional context in comments.

1 Comment

as you can see in my code, I am already using the Add function.
1

To just add a control to the current Form, the code from Frederick is correct, like this:

var thisObj = new Label { Name = "One", Text = "Some Text" }; Controls.Add(thisObj); 

It is normal that Form1 does not show, you never call the Show() method. If you want to show Form1 with the new Label added this is the code:

var form = new Form1(); var thisObj = new Label { Name = "One", Text = "Some Text" }; form.Controls.Add(thisObj); form.Show(); 

The form that will be loaded by default in your WindowsForms application is defined in the file 'Program.cs':

Application.Run(new Form1); 

Comments

0

I worked around this by sending an instance of the Form through the constructor of the class.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.