Your question is missing some important context. I built a simple form using your code and it ran just fine. Form1
is just the default form that shows up when you create the new device application.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
AddMyHardcodedAdditions();
}
void AddMyHardcodedAdditions()
{
TextBox tb = new TextBox();
tb.Location = new Point(10, 10);
Panel pn = new Panel();
pn.Dock = DockStyle.Fill;
pn.Controls.Add(tb);
this.Controls.Add(pn);
}
}
EDIT To address your comment.
I believe you are misunderstanding the this keyword. If you're building this from MyClass
and it has no Controls
collection, you cannot call this.Controls ...
anywhere with MyClass
without a compilation error.
You could add an InsertControl
method on your Form or Control class like so:
public void InsertControl(Control control)
{
this.Controls.Add(control);
}
... and call it from your MyClass
code like so:
MyForm myForm = ...; //set by you at some point
...
void AddMyHardcodedAdditions()
{
...
myForm.InsertControl(pn);
}