I have created a textbox in a Windows Forms application that starts out at a height for entering text in a single line. But I would like the textbox to automatically increase its height if the user enters text that is wrapped within the control.
Currently, for this textbox, I have the properties multiline and wordwrap set to true. I've tried using the TextChanged event to determine when the text has been wrapped but I'm unable to find any property that will help me with this. The Lines property does not provide any help with wrapped text; only for text that the user has hit enter to begin a new line.
How can I get my textbox to expand its height each time the text wraps past the width of the textbox?
If you're willing to use a RichTextBox instead (which, in my experience, is kind of a grumpy control that comes with lots of quirks), you can use the ContentsResized event, which gives you the new required size:
Unfortunately, I can't provide specifics but you are going to need to probably do a custom implementation.
I'd derive a new text box type -- ExpandableTextBox -- and then you'll need to implement it by hand.
This also seems relevant to what you are looking for: http://social.msdn.microsoft.com/Forums/en-US/winforms/thread/11dfb280-b113-4ddf-ad59-788f78d2995a
Same kind of idea as others have posted, put this in your textChanged event:
You will need some kind of minimum height, and possibly to specify some padding, but this does work.
I'm using the code below with success until about the 10th line, then it gets 1 character off, but this works for me. Don't ask me about the random numbers like - 7 and - 12, they have something to do with padding
I just wrote this for a label control for a different project. I got the code off of code project somewhere I think. Changing it to a Textbox should be as simple as changing the base.
AdamSane's post was helpful but the textbox didn't grow. I'd to make some modifications. My mods are below: