Clement Herreman
Clement Herreman

Reputation: 10536

Align TextBox and Label text

I'm designing a UI, and I found myself itching my head : how can I align a TextBox text and a label text, which are side by side.

In design mode, it's easy, you move one with your mouse, a purple line appears and voila ! the alignment is good, but mine are code generated, so how can i align their contents ?

Thank you !

Edit : Layout is something I can't use (I don't make the rules, my boss do..)

Upvotes: 8

Views: 15844

Answers (3)

Roman Starkov
Roman Starkov

Reputation: 61512

I like to use the FlowLayoutPanel (instead of the TableLayoutPanel) for this purpose because you don't need to fiddle with columns. Remember to remove both the Top and the Bottom anchors on every control to make them vertically centered, and set FlowLayoutControl.AutoSize = true and AutoSizeMode = GrowAndShrink.

Edit: regarding your restriction that "Layout is something I can't use": so you want instead to access the purple text baseline snapline position programmatically, at runtime? This is possible, but it's unlikely to be faster than layouts because only the designer for the control knows where it is, so you will have to create designers for all controls you need this for.

This question has some code that can be used as a starting point, but as I said, it's probably not the right approach either given the performance constraints.

Upvotes: 15

Henk Holterman
Henk Holterman

Reputation: 273701

Take a look at the TableLayoutPanel. Still not so easy to get the baseline match but by vertically centering the label and setting the Rows to AutoSize you will get something that is ordered and flexible.

Upvotes: 4

Matt Jacobsen
Matt Jacobsen

Reputation: 5884

then use the X, Y, Width, Height properties of each control (inherited from Control).

int padding = 5;
textbox.Y = label.Y;
textbox.X = label.Width + padding

Upvotes: 1

Related Questions