I can't believe there is still no really elegant way. This is what I puzzled out:
textBox.Height += textBox.GetPositionFromCharIndex(textBox.Text.Length - 1).Y
+ 3 + textBox.Font.Height - textBox.ClientSize.Height;
This works by determining the pixel coordinates of the last character of the text.
You can execute this after setting the contents, i.e. in OnLoad
of the Form
or OnTextChanged
of the TextBox
control. If the fixed width changes when the user resizes the form, you should also take care of that, i.e. OnResize
or OnClientSizeChanged
.
TextBox
supports the AutoSize
property. However, it is already set to true
by default, and it is not shown in the property editor or IntelliSense. It is just for font height changes and does not work when using MultiLine = true
:( - this is not mentioned in the documentation.
Other options might include using a different control, like RichTextBox
or Label
. I didn't try yet, but it seems that a Label supports AutoSize much better.