I'd suggest using Graphics.MeasureString
.
First you create a Graphics
object, then call MeasureString
on it, passing the string and the textbox's font.
Example
string text = "TestingTesting\nTestingTesting\nTestingTesting\nTestingTesting\n";
// Create the graphics object.
using (Graphics g = textBox.CreateGraphics()) {
// Set the control's size to the string's size.
textBox.Size = g.MeasureString(text, textBox.Font).ToSize();
textBox.Text = text;
}
You could also limit it to the vertical axis by setting only the textBox.Size.Height
property and using the MeasureString
overload which also accepts int width
.
Edit
As SLaks pointed out, another option is using TextRenderer.MeasureString
. This way there's no need to create a Graphics
object.
textBox.Size = TextRenderer.MeasureString(text, textBox.Font).ToSize();
Here you could limit to vertical resizing using Hans' technique, passing an extra Size
parameter to MeasureString
with int.MaxValue
height.