Search code examples
c#textboxgroupbox

How do I center the textboxes in the group box?


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?


Solution

  • 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;