Doug
Doug

Reputation: 5328

Winforms Control Placeholder

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

Upvotes: 4

Views: 3283

Answers (2)

Adam Lear
Adam Lear

Reputation: 38778

It doesn't work because what's added to the Controls collection is the instance of System.Windows.Forms.Control that you added in the constructor. You then change the object that _placeholder points to to a textbox control, but you never add that textbox to the form's Controls collection.

Upvotes: 1

Reed Copsey
Reed Copsey

Reputation: 564701

This won't work, as written, because the original placeholder is still the reference added to the controls. You could fix it by doing:

public void ChangeToTextBox()
{
  this.Controls.Remove(_placeholder); // Remove old
  _placeholder = new TextBox();
  this.Controls.Add(_placeholder); // Add new
}

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.

Upvotes: 5

Related Questions