0

How to change the size of a textbox in C#

I admit, the title sounds almost trivial. But on the second sight, it is not so easy to change the size of a TextBox control in C#, because a TextBox does not have the AutoSize property. For other controls you can set the AutoSize property to false and then change the height (height-property). For the TextBox control this is unfortunately not the case.

Nevertheless you can set the height of a TextBox by using a small workaround. The trick is as follows:

textBoxTest.Multiline = true;
textBoxTest.MinimumSize = new Size(150, 24);
textBoxTest.Size = new Size(150, 24);
textBoxTest.Multiline = false;

First you have to set the multiline property to true. Then you can adjust, according to your mood, the minimum-size and the size property to change the size of the TextBox. When you’re done, you set the Multiline property back to false. The TextBox maintains the set size just yet. It’s that simple

Who still wonders, why you should need that, if the TextBox adapts itself to its size, should set the border style to “None” and change the font size. Namely, one would like to display a TextBox without frame and with a slightly larger font. In this case it must be said that the automatic resizing does not work correctly. This can be well seen in the following screen shot:

C# TextBox Height - TextBox Höhe verändernOn the form there are four text boxes:

1: Font size and border style unchanged
2: Increased font size, border style unchanged
3: Increased font size, border style = “none”
4: Increased font size, border style = “none”, the size of the text box manually changed

As you can see in TextBox 3, the auto-size function does not work correctly with deactivated border and certain characters are not displayed correctly.

For this problem the above show workaround can help, as you can see by the fourth TextBox.

About the author: This article, as well as 139 more on en.code-bude.net, were published by Raffi. – Since 2011 I've been blogging here and on code-bude.net, the german counterpart, about programming and my software, write tutorials and try to share my knowledge, as well as possible, with my readers. Furthermore I write at derwirtschaftsinformatiker.de on subjects of my studies.
  //    •  • Facebook  • Twitter