Resize a TextBox to fit its text in C#

As you type, this example resizes its TextBox to fit its contents. 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's text will be when rendered. It then resizes the TextBox so it has room to display the text. It adds a little to the TextBox's height to make everything fit. If you don't add a little bit, the lines don't all fit.

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

// Make the TextBox fit its initial text.
private void Form1_Load(object sender, EventArgs e)
{
    txtContents.Multiline = true;
    txtContents.ScrollBars = ScrollBars.None;

    AutoSizeTextBox(txtContents);
}

This code makes the TextBox multiline and removes its scroll bars. It then calls the AutoSizeTextBox method to initially size the TextBox.

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

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

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.