How can I automatically increase/decrease TextBox and Windows Form size according to text Length?
Asked
Active
Viewed 1.4k times
4
-
Use the Autosize property http://msdn.microsoft.com/en-us/library/system.windows.forms.textboxbase.autosize.aspx – Jodrell Nov 14 '11 at 11:53
-
@Jodrell this doesn't change the width of a TextBox, only the height. – Connell Nov 14 '11 at 12:07
4 Answers
10
You can try overriding the OnTextChanged event, then changing the Width depending on the size of the text.
protected override OnTextChanged(EventArgs e)
{
using (Graphics g = CreateGraphics())
{
SizeF size = g.MeasureString(Text, Font);
Width = (int)Math.Ceiling(size.Width);
}
base.OnTextChanged(e);
}

Connell
- 13,925
- 11
- 59
- 92
-
I've never tried it on a TextBox TextChanged either ;) but it works for me when I'm resizing a UserControl based on an inner Label's Text. – Connell Nov 14 '11 at 16:40
-
i always followed above answer what I proposed. I never worked on Override – Sandy Nov 14 '11 at 16:52
-
@rapsalands without overriding, all `OnTextChanged(EventArgs e)` does is fire the events. They do exactly the same thing so it'll still work. – Connell Nov 14 '11 at 17:23
-
no no...i know it will still work and i was just saying i have not worked on override techniques ever. I am kinda new in this field, got to learn and explore a lot. I liked your technique and that's why added this question in my favorites so I can refer it anytime. Thanks. – Sandy Nov 14 '11 at 19:35
-
@rapsalands it certainly has its benefits :) a good field to learn. cheers! – Connell Nov 14 '11 at 21:55
2
Try this, it will also work...
Here I have taken 100 as minimum width of textbox. "txt" is TextBox.
const int width = 100;
private void textBox1_TextChanged(object sender, EventArgs e)
{
Font font = new Font(txt.Font.Name, txt.Font.Size);
Size s = TextRenderer.MeasureText(txt.Text, font);
if (s.Width > width)
{
txt.Width = s.Width;
}
}
Hope it helps.

Sandy
- 11,332
- 27
- 76
- 122
1
Here is better solution. Scenario is: I have a textbox that Filled on form (usercontrol). So, I want to change Form Height each time number of line in textBox change, but its height is not less than MinHeight (a constant)
private void ExtendFormHeight()
{
int heightChanged = txtText.PreferredSize.Height - txtText.ClientSize.Height;
if (Height + heightChanged > MinHeight)
{
Height += heightChanged;
}
else
{
Height = MinHeight;
}
}
Hope this help!

zquanghoangz
- 663
- 5
- 11
-
Any ideas on how you would do this for a text block? I am passing in a set string from my code. – Zarif Rahman Feb 15 '23 at 20:45