Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using anchor property with dynamically added controls

Tags:

c#

winforms

I'm adding some textboxes to a form dynamically at runtime. Everything works fine i.e. the textboxes are aligned, anchored and automatically resizes until the form is maximized. On maximizing the form, the textboxes are added to the same location while the form was not maximized. This causes a misalignment of the textboxes.

How can I ensure that all the textboxes are at the same location and of the same size both while the windowstate is normal as well as maximized?

EDIT:

Btw I'm using C#

EDIT:

Would a flowlayoutpanel be useful here?

like image 393
tijuthomas Avatar asked Nov 05 '22 21:11

tijuthomas


1 Answers

It's a quite old question, but maybe i'm able to answer it.

After reading all your comments, i think i can summarize your problem to this:

  • You have a form at a specific size and add some controls at runtime at a specific location with anchor set to Top | Right.
  • If you just display the form and let the controls appear everything works fine
  • If you maximize your form (or change the size of it) your controls won't be appear anymore at the correct location you want.

To get rid of this problem you can try some different approaches:

  1. Use a FlowLayoutPanel, take care for the FlowDirection and maybe just create all your needed controls beforehand and just toggle the visible state.
  2. Use correct values for the location of your newly created controls.

The second point is the error you have (i think). You found someway to calculate the location of your control if your form has it's original size. To get the correct position if the size of the form has changed (e.g. maximized) you have to consider several factors.

  • The delta values from your default size to your current size.
  • The Anchor(s) you wish to set on your control.

In your case you'd like to put a control which is anchored Top | Right, but the location is set by Top | Left. In that case you have to calculate the difference between the control.location.x and the form.width in it's default size. Then you take this difference and subtract it from the form current width. Now you can place your control at this position (cause Top never changes through a resizing). If you have a Anchor at Bottom | Right you have to calculate the same with control.location.y and form.height.

The behaviour and calculation if no anchor, for Top | Bottom or Left | Right are set is left as an exercise to the reader. ;-)

Last but not least there is also another hacky way to get your control at the right position:

  • If you like to place a new control somewhere change the Form.Visible to false
  • Save the form state, size and location
  • Change them to your default values
  • Add the controls you want
  • Restore the formerly saved values
  • Make the form visible again.
like image 126
Oliver Avatar answered Nov 15 '22 06:11

Oliver