I am trying to add a System.Windows.Forms.Control to a given forms control collection. I do this by creating a private field of type control and then instantiating this field to a new instance of System.Windows.Forms.Control in the constructor.
At runtime I am trying to change the type of the _placeholder variable to a TextBox, by doing something like in the following code example. So basically I am trying to have a placeholder of type Control and change it to another control like a TextBox or Label at runtime. My issue is that nothing shows up on my form? Any insight would be appreciated.
public class MyForm : Form
{
System.Windows.Forms.Control _placeholder = null;
public MyForm()
{
_placeholder = new System.Windows.Forms.Control();
this.Controls.Add(_placeholder);
ChangeToTextBox();
}
public void ChangeToTextBox()
{
_placeholder = new TextBox();
}
}
This won’t work, as written, because the original placeholder is still the reference added to the controls. You could fix it by doing:
That being said, if this is going to go into the same location on your form, you might want to consider putting a Panel there instead, and just adding the TextBox to the Panel. This will prevent the need to remove existing controls since it’s just adding one in.