Click here to Skip to main content
15,885,004 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
I'm creating a software which utilizes textboxes and labels. I need the textboxes to resize if the form is resized; and I want the labels to stay at the center of the textboxes

Making the textboxes resize wasn't hard, I just anchored them to the left, right and top.


This is the problem I'm having:

I thought I could get them to work by applying the same anchoring settings to the textbox but that's not working.


It looks okay when the form first loads. See here^

But when you resize the forms, things go wrong. Click here to see it

How do I do this?
Thanks in advance!! :)
Posted
Updated 30-Jul-15 2:08am
v6
Comments
stibee 30-Jul-15 8:20am    
WPF or winforms.... please show the code from your view... easier to help

2 choices :

1 : keep anchor to left and right for your label but change the following properties :
- AutoSize = false
- TextAlign = TopCenter

2 : anchor the label only to the top (remove left and right)

First method will change the label size but the text will be centered in the resized control. Inconvenient : when the form is reduced, the label will be reduced and the text may disappear.

Second method will move the label adding the same distance on its left size and on its right size. if the label is first centered, it will remain centered. but if it is align on the left (or right) it will move when the form increase or may disappears when the form is reduced.

Same behaviour can be used verticaly when not anchord to top and bottom.

And it can be used for any .Net Controls (not only labels)

Edit: This solution is for WinForms, for WPF, just change the "HorizontalAlignment" property to "Center"
 
Share this answer
 
v2
Comments
CHill60 30-Jul-15 9:15am    
5'd for the first one. Neat.
Assuming you're developing for WinForms, it just takes a bit o' number crunching to re-align the labels. Off the top of my head (and before coffee), this should do it:
C#
myLabel.X = myTextBox.Left + (myTextBox.Width - myLabel.Width)/2;
Call in your form's Resize handler.

/ravi
 
Share this answer
 
Comments
Philippe Mori 30-Jul-15 12:29pm    
Since you can do it directly from the designer setting anchors and aligment correctly, it is not required to do that (see solution 2).
Ravi Bhavnani 30-Jul-15 12:42pm    
Agreed - the AutoSixe=False, Anchor and TextAlign=TopCenter is a much nicer way!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900