Resize text box and form size to fit text length

How can I automatically increase / decrease the size of TextBox and Windows Form according to the text Length?

+4
source share
4 answers

You can try to override the OnTextChanged event, and then change 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); } 
+8
source

Try it, it will work too ...

Here I took 100 of the minimum width of the text box. "txt" is a 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 this helps.

+2
source

Here is the best solution. Scenario: I have a text field populated with a form (usercontrol). So, I want to resize the form every time the number of lines in the text field changes, but its height is not less than MinHeight (constant)

 private void ExtendFormHeight() { int heightChanged = txtText.PreferredSize.Height - txtText.ClientSize.Height; if (Height + heightChanged > MinHeight) { Height += heightChanged; } else { Height = MinHeight; } } 

Hope this help!

+1
source

set the width to "Auto in properties"

-2
source

Source: https://habr.com/ru/post/1381111/


All Articles