Limite textbox text to its space

encami

Newcomer
Joined
Jan 11, 2012
Messages
3
Hello, I need a textbox in a windows form that only accept text that fit inside its space. I don't find any property to do this. Any help? Thank you in advance
 
It depends on exactly how you would like to limit the length of the text. It sounds like you want to limit the text to how much fits in the control visually. You can specify a maximum number of characters using the MaxLength property. That's the simplest solution, but may not work exactly the way you want.


If you want to limit the input by how much text the control can hold visually, you can handle the TextChanged event and see if the new text fits in the text box. If not, revert to the previous text. In order to see whether the new text fits, you would want to use a Graphics object (PSA: Please allocate and dispose responsibly) and call the MeasureString function (you may need to specify a StringFormat or some other info if the measurements don't seem right). When trying to change the textbox behavior like this, it's often difficult to get the cursor to act in an intuitive way (you'll see what I mean if you try it).
 
I tried TextChanged and MeasureString and found that blank spaces not compute in the size calculated. I found a way to take into account the blank spaces but I note that the string that I need to edit has right-leading spaces and need to put the edit mode into overwrite, not insert. Don't know how to do this...
Thank you for your help!
 
Finally I managed to get data trimmed (without leading spaces) from the database and got the behavior that I needed.
 
Back
Top