In a C# form, I have a panel anchored all sides, and inside, a textbox, anchored top/left/right.
When text gets loaded into the textbox, i want it to auto expand itself vertically so that I don't need to scroll the textbox (scroll the panel at most, if there is more text that doesn't fit the panel). is there any way to do this with a textbox? (i'm not constrained to use this control so if there's another control that fits the description, feel free to mention it)
I'll assume this is a multi-line text box and that you'll allow it to grow vertically. This code worked well:
You ought to do something reasonable when the text box is empty, like setting the MinimumSize property.
You could anchor it to the bottom, that will ensure that the textbox is resized vertically when ever the form to which it belongs is resized. Also, a textbox that changes its size might not be an elegant thing since it might disrupt the way that other components are displayed. Why don't you give it a maximum size instead of having it resized?
Try this approach:
aspx.cs code
aspx code
You can use a Label, and set AutoSize to
true
.I'd suggest using
Graphics.MeasureString
.First you create a
Graphics
object, then callMeasureString
on it, passing the string and the textbox's font.Example
You could also limit it to the vertical axis by setting only the
textBox.Size.Height
property and using theMeasureString
overload which also acceptsint width
.Edit
As SLaks pointed out, another option is using
TextRenderer.MeasureString
. This way there's no need to create aGraphics
object.Here you could limit to vertical resizing using Hans' technique, passing an extra
Size
parameter toMeasureString
withint.MaxValue
height.The current selected answer does NOT handle lines with no spaces such as "jjjjjjjjjjjjjjjjjjjj"x1000 (think about what would happen if someone pasted a URL)
This code solves that problem: