Resize a TextBox to fit its text in C#

[resize a TextBox]

This example shows how you can resize a TextBox to fit its contents as the user types. The key is the following AutoSizeTextBox method.

// Make the TextBox fit its contents.
private void AutoSizeTextBox(TextBox txt)
    const int x_margin = 0;
    const int y_margin = 2;
    Size size = TextRenderer.MeasureText(txt.Text, txt.Font);
    txt.ClientSize =
        new Size(size.Width + x_margin, size.Height + y_margin);

The method uses the TextRenderer class’s MeasureText method to see how big the TextBox control’s text will be when rendered. It then resizes the TextBox so it has room to display the text. It adds a little extra to the TextBox control’s height to make everything fit. (If you don’t add a little extra, the lines don’t all fit.)

When the program starts, the form’s Load event handler uses the following code to prepare the TextBox.

// Prepare the TextBox.
private void Form1_Load(object sender, EventArgs e)
    // Register the TextChanged event handler.
    txtContents.TextChanged += txtContents_TextChanged;
    txtContents.Multiline = true;
    txtContents.ScrollBars = ScrollBars.None;

    // Make the TextBox fit its initial text.

This code registers the txtContents_TextChanged event handler to handle the control’s TextChanged event. It also makes the TextBox multiline and removes its scroll bars. The code then calls the AutoSizeTextBox method to initially size the TextBox.

The TextChanged event handler shown in the following code also calls AutoSizeTextBox to make the TextBox fit its text when the text changes.

// Make the TextBox fit its new contents.
private void txtContents_TextChanged(object sender, EventArgs e)
    AutoSizeTextBox(sender as TextBox);

That’s all there is to it! An auto-sizing TextBox is an unusual user interface feature, but it’s not too hard to build.

Download Example   Follow me on Twitter   RSS feed   Donate

This entry was posted in controls, user interface and tagged , , , , , , , , , , , . Bookmark the permalink.

1 Response to Resize a TextBox to fit its text in C#

  1. Pingback: Resize a RichTextBox to fit its contents in C# - C# HelperC# Helper

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.