I'm writing a program where the user should be able to write text in a TextBox
. I'd like the TextBox
to resize itself, so it fits to the content. I've tried the following:
private void textBoxTitle_TextChanged(object sender, TextChangedEventArgs e) { System.Drawing.Font myFont = new System.Drawing.Font("Verdana", 8); System.Drawing.SizeF mySize = e.Graphics.MeasureString("This is a test", myFont); this.textBoxTitle.Width = (int)Math.Round(mySize.Width, 0); }
I get an error saying that Graphics
doesn't work for TextChangedEventArgs
. Is there another way I can resize the TextBox
?
C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...
What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.
Compared to other languages—like Java, PHP, or C#—C is a relatively simple language to learn for anyone just starting to learn computer programming because of its limited number of keywords.
In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.
You should try a code something like below. It has worked for me well.
private void textBox1_TextChanged(object sender, EventArgs e) { Size size = TextRenderer.MeasureText(textBox1.Text, textBox1.Font); textBox1.Width = size.Width; textBox1.Height = size.Height; }
For more information refer to TextRenderer.MeasureText()
I am adding this answer as I do not see the fixed width
aspect of a textbox being discussed in any of the other. If you have a fixed width for your textbox, and you want to adjust only its height you can do something like the following:
Something like this gives the height of the text as how it is drawn in the multiline wordwrapped textbox itself:
SizeF MessageSize = MyTextBoxControl.CreateGraphics() .MeasureString(MyTextBoxControl.Text, MyTextBoxControl.Font, MyTextBoxControl.Width, new StringFormat(0));
I am not sure what StringFormat
should be but the values StringFormatFlags
do not seem to apply to a default TextBox
make up.
Now with MessageSize.Height
you know the height of the text in the textbox.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With