Question

So here's the important part code:

this.textBoxes[i].Location = new System.Drawing.Point(x, 20 + i * 25);
this.textBoxes[i].Size = new System.Drawing.Size(35, 20);

textBoxes[i].Parent = this;
this.groupBox1.Controls.Add(textBoxes[i]);

Suppose that the size of the groupBox1 is changable. How do I make it so that the textboxes will be in the middle of the group box, where the distance between the left side of the textbox and the left side of the group box is the same as the difference between the right side of the textbox and the length (right side) of the group box?

Was it helpful?

Solution 2

try

this.textBoxes[i].Anchor = AnchorStyles.None;
this.textBoxes[i].Dock = DockStyle.None;
Point pt = this.groupBox1.DisplayRectangle.Location;
pt.X += (this.groupBox1.DisplayRectangle.Width - this.textBoxes[i].Width)/2;

pt.Y += (this.groupBox1.DisplayRectangle.Height - this.textBoxes[i].Height)/2;

this.textBoxes[i].Location = pt;

OTHER TIPS

Assuming you've positioned your TextBoxes correctly in the middle of the GroupBox, you should be able to disable all anchors on the control and it will sorta float in the center.

As the parent control (GroupBox) is resized, a control inside it with no anchors should change position so that the relative margin between the control and the GroupBox remains the same on all sides.

Try this:

this.textBoxes[i].Anchor = AnchorStyles.None;

By default, controls usually anchor to their parent control on the left and top sides.

When a control is anchored to an edge of its container, the distance between the control and the specified edge remains constant when the container resizes. For example, if a control is anchored to the right edge of its container, the distance between the right edge of the control and the right edge of the container remains constant when the container resizes. A control can be anchored to any combination of control edges.

Here's the part that concerns what you're trying to do:

If the control is anchored to opposite edges of its container (for example, to the top and bottom), it resizes when the container resizes. If a control has its Anchor property set to AnchorStyles.None, the control moves half of the distance that the container of the control is resized. For example, if a Button has its Anchor property set to AnchorStyles.None and the Form that the control is located on is resized by 20 pixels in either direction, the button will be moved 10 pixels in both directions.

You can read more about AnchorStyles on MSDN.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top