Earlier today I was looking for an easy way to force users to enter Uppercase text into a textbox on a web form I was creating. There are a few different solutions out there, including some Javascript functions to call when the user types into the text box, but I wanted something that wouldn’t require too much javascript (or none at all). There were also some solutions that would allow the user to type whatever, then when the textbox loses focus, it would change to upper case. Again, not bad, but not what I wanted. What I wanted was, regardless of what the user entered, the textbox would display uppercase.
Step in CSS! There is a CSS property text-transform, which can be either capitalize, lowercase or uppercase. What this will do will force the text entered to display as capitalized, lowercase or uppercase (whatever you choose). Now, this looked like a winner, as there was no scripting needed. However, this only does half the job. All the CSS class will do is display what is entered as uppercase, not actually convert it to uppercase.
The fix… when you get the text from the textbox in your codebehind, use the .ToUpper() method to convert the entered text to uppercase.
In Summary
- Add a CSS class with text-transform: uppercase;
- Add this CSS class to any textbox you want to have uppercase text.
- When getting the text from the textbox, use the .ToUpper() method to convert the text to uppercase.
For me, this was the best solution, as it does not require any javascript, uses a simple CSS class, and only a very minor modification to the codebehind to make sure the uppercase text is taken as uppercase.
I hope someone else finds this helpful.