C# WinForms Vertical Alignment for TextBox, etc
If you're turning off AutoSize
on a control, it must be a Label
, since TextBox
doesn't have an AutoSize
property. The TextAlign
property of a Label
is of type ContentAligment
, so you can set both horizontal and vertical alignment.
For various boring reasons, TextBoxes
in Windows are intended to auto-adjust their heights to the font used. To control the height and vertically center the text, you can quickly create a custom UserControl
, that you can use for replacing all your TextBoxes
with.
On your UserControl
, set the BorderStyle
to Fixed3D
and the BackColor
to System.Window
. Add a TextBox
and set its BorderStyle
to None
. In the Resize event for the control, add code that makes the TextBox
the same width as the user control's client area (accounting for the border pixels) and left-aligns it (i.e. textBox1.Left = 0;
) and vertically centers it (e.g. textBox1.Top = (this.Height - textBox1.Height) / 2;
).
Finally, add to the user control any TextBox
-type properties and events you need (probably just Text and TextChanged
, I would guess), and wire them up so that they pass through to the TextBox
inside your control, like this:
public string Text
{
get => textBox1.Text;
set => textBox1.Text = value;
}
If you wanted to get super-fancy with this, you could even replace your user control's TextAlign
property with one that is actually of type ContentAlignment
(like the Label) and then align the inner TextBox
to match.
This same approach works for a ComboBox
, although it will look slightly odd. With the ComboBox
, you set its FlatStyle
property to Flat - otherwise you deal with it the same as a TextBox
. It will look odd because the drop-down arrow box won't be quite at the top and bottom of the panel.