[C# Helper]
Index Books FAQ Contact About Rod
[Beginning Database Design Solutions, Second Edition]

[Beginning Software Engineering, Second Edition]

[Essential Algorithms, Second Edition]

[The Modern C# Challenge]

[WPF 3d, Three-Dimensional Graphics with WPF and C#]

[The C# Helper Top 100]

[Interview Puzzles Dissected]

[C# 24-Hour Trainer]

[C# 5.0 Programmer's Reference]

[MCSD Certification Toolkit (Exam 70-483): Programming in C#]

Title: Resize a TextBox to fit its text in C#

[Resize a TextBox to fit its text in C#]

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. AutoSizeTextBox(txtContents); }

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 the example to experiment with it and to see additional details.

© 2009-2023 Rocky Mountain Computer Consulting, Inc. All rights reserved.