I don't know if I've been too clear with the title so I apologize if I haven't. I put an example of what I mean, very simple, but I imagine that it will be extensible to any Windows Forms control. I create a textBox
in a "textBox1" form , now by code, I instantiate a textBox
and Text
assign the value "test" to its property:
textBox cajaTextoDinamica = new textBox();
cajaTextoDinamica.Text = "prueba";
In my head, it made sense that if I typed : textBox1 = cajaTextoDinamica;
the one on textBox1
the form would be replaced by the dynamically generated one, but it doesn't. However, even though such a control is not displayed on the form, the property text
now txtBox1
has the value "test" even though it does not display it. I hope I have explained myself well enough and I would appreciate it if you could tell me what I am doing wrong.
What you suggest can be done. I don't see much point in changing one control for another of the same type, but since you mention that it's about learning, I can think of a hypothetical case that could be solved by changing one control for another.
Let's say a form is required where the user has to choose option A or option B. If he chooses option A, he has to write some information in a TextBox, but if he chooses option B, he has to select a value in a ComboBox.
To solve it, we place a Label control on the form that will serve to mark the position of the place where we want the final control to be, and we assign the following properties to it:
AutoSize = false
, this will allow us to change the size that will be used to assign it to the final control.TabIndex
this property defines the traversal order of the controls when the tab key is pressed.Name = label1
although it can be any name.The way to replace the control is as follows:
This example should serve to replace any control. Note that it is necessary to add validations to ensure that the control exists before removing it or that it does not exist before adding it.
For example: