Placeholder for Winforms Management

I am trying to add System.Windows.Forms.Control to this form management collection. I do this by creating a personal type control field and then creating this field for a new instance of System.Windows.Forms.Control in the constructor.

At runtime, I try to change the type of the _placeholder variable in a TextBox by doing something like the following code example. So basically I'm trying to have a placeholder like Control and change it to another control like TextBox or Label at runtime. My problem is that nothing appears 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(); } } 
+4
source share
2 answers

This will not work as written because the original placeholder still refers to the controls. You can fix this by doing:

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

If it is said that this will go to the same place in your form, you can consider placing Panel instead, and simply adding a TextBox to the panel. This will prevent the need to remove existing controls as it simply adds it.

+5
source

This does not work because adding to the Controls collection is an instance of the System.Windows.Forms.Control that you added to the constructor. Then you modify the object that _placeholder points to the text field control, but you never add this text field to the Controls form collection.

+1
source

Source: https://habr.com/ru/post/1337563/


All Articles