开发者

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.Cont开发者_运维技巧rol _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:

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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜