Winform - Groupbox & Controls?
In a Winform I have a groupbox and in it several Textbox controls. If I delete the Groupbox the Textboxes get deleted as well. They are somehow tied to the Groupbox though I didn't do anything knowingly for this to happen. Question - how can I remove this connection, so that I can delet开发者_运维技巧e the groupbox and still have the textboxes on the form?
Child controls have a Parent property. If you delete their parent, Windows Forms automatically calls Dispose() on the children as well. Which is one reason you never have to explicitly call Dispose() yourself on the child controls when you close a form.
Getting what you want is easy enough, add the children to the form with the this.Controls.Add() method. WF automatically removes them from the groupbox since a child control can have only one Parent. Some sample code:
private void button1_Click(object sender, EventArgs e) {
int nextTab = 0;
foreach (Control ctl in this.Controls) nextTab = Math.Max(nextTab, ctl.TabIndex);
Point offset = groupBox1.Location;
for (int ix = groupBox1.Controls.Count - 1; ix >= 0; --ix) {
Control ctl = groupBox1.Controls[ix];
ctl.Location = new Point(ctl.Left + offset.X, ctl.Top + offset.Y);
ctl.TabIndex += ++nextTab;
this.Controls.Add(ctl);
}
groupBox1.Dispose();
groupBox1 = null;
}
In the Designer.cs file you'll have a series of lines of code like :
this.groupBox1.Controls.Add(this.textBox2);
this.groupBox1.Controls.Add(this.textBox1);
change them to say :
this.Controls.Add(this.textBox2);
this.Controls.Add(this.textBox1);
this will make their container the form rather than the groupbox, and you can delete the groupbox after that. This will however move the textboxes, as their Position values are relative to their container which was the Groupbox.
Move the textboxes out of the groupbox before deleting it.
Another option would be to hand-edit the designer-generated file (Foo.Designer.cs) and remove the groupbox there. The member declaration is at the very end of the designer file, while all setup work gets done in InitializeComponent()
. If you remove the member declaration first the compiler errors should point you to places where you still need to delete some lines. It kinda works but as always, be careful when hand-editing auto-generated files :-).
精彩评论