I want to remove and add a control at runtime on a Windows Forms form. The problem is, that the control must have the exact same size, location and anchors as another one.
If the user opens the window and a certain criteria is fulfilled, I want to delete the old control and replace it by another.
So, I tried this:
RichTextBox InsideText = new RichTextBox();
InsideText.Location = InsideBox.Location;
InsideText.Size = InsideBox.Size;
Controls.Remove(InsideBox);
Controls.Add(InsideText);
But, as expected, it didn't work. The InsideBox
is not removed and the InsideText
not added.
What am I doing wrong? Is there a开发者_开发知识库 better approach to this?
I'd suggest that the easier way would be to:
- Add a panel in the correct location with the correct anchor, etc. set.
- Add control1 inside that panel set to full
Dock
- Just remove control1 and add control2 inside that panel instead and set it to Dock.
Then all the size stuff, etc. is done by the one Panel instead of having to copy that around.
精彩评论