• After more than 30 years running websites and forums I am retiring.

    I have made many friends through the years. I will cherish my time getting to know you. I wish you all the best. This was not an easy decision to make. The cost to keep the communities running has gotten to the point where it's just too expensive. Security certificates, hosting cost, software renewals and everything else has increased threefold. While costs are up ad revenue is down. It's no longer viable to keep things running.

    All sites will be turned off on Thursday 30 November 2023. If you are interested in acquiring any of the websites I own you can Email Schwarz Network.

Limite textbox text to its space

encami

Newcomer
Joined
Jan 11, 2012
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
 

snarfblam

Ultimate Contributor
Joined
Jun 10, 2003
Location
USA
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).
 

encami

Newcomer
Joined
Jan 11, 2012
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!
 

encami

Newcomer
Joined
Jan 11, 2012
Finally I managed to get data trimmed (without leading spaces) from the database and got the behavior that I needed.
 
Top Bottom