Convert Text to Uppercase while typing in Text box
Asked Answered
V

7

21

I am new in Visual Studio and using visual Studio 2008. In a project I want to make all text in uppercase while typed by the user without pressing shift key or caps lock on. I have used this code

TextBox1.Text = TextBox1.Text.ToUpper();

but it capitalize characters after pressing Enter key.

I just want that characters appear in uppercase while typing by the user without pressing shift key or without caps lock on.

Total page code is as...

public partial class Test : System.Web.UI.Page 
 {
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void TextBox1_TextChanged(object sender, EventArgs e)
    {
        TextBox1.Text = TextBox1.Text.ToUpper();

    }
}

Have any one any solution, please guide me.

Vinny answered 3/5, 2014 at 12:42 Comment(1)
Put the code in OnKeyPress event: msdn.microsoft.com/en-us/library/…Holdall
P
51

There is a specific property for this. It is called CharacterCasing and you could set it to Upper

  TextBox1.CharacterCasing = CharacterCasing.Upper;

In ASP.NET you could try to add this to your textbox style

  style="text-transform:uppercase;"

You could find an example here: http://www.w3schools.com/cssref/pr_text_text-transform.asp

Provencher answered 3/5, 2014 at 12:51 Comment(5)
Hello Steve Thanks for your reply. As Stated I am using visual Studio 2008 and there is no option in property named "CharacterCasing". Can you suggest me how to write this code.Vinny
Just to put things in perspective. Do you need to handle the problems outlined in the other answers? (i.e. capitalization for specific cultures)Provencher
CharacterCasing is a property of WINFORMS TextBox. Now, I see from the today edit that you are using ASP.NET so I don't think that this could be applied.Provencher
Found something for ASP.NET, not tested. Try it and let me know.Provencher
style="text-transform:uppercase;" it only visibly make Uppercase if you access it server side you will get lowercase :(.Repetend
O
9

Edit (for ASP.NET)

After you edited your question it's cler you're using ASP.NET. Things are pretty different there (because in that case a roundtrip to server is pretty discouraged). You can do same things with JavaScript (but to handle globalization with toUpperCase() may be a pain) or you can use CSS classes (relying on browsers implementation). Simply declare this CSS rule:

.upper-case
{
    text-transform: uppercase
}

And add upper-case class to your text-box:

<asp:TextBox ID="TextBox1" CssClass="upper-case" runat="server"/>

General (Old) Answer

but it capitalize characters after pressing Enter key.

It depends where you put that code. If you put it in, for example, TextChanged event it'll make upper case as you type.

You have a property that do exactly what you need: CharacterCasing:

TextBox1.CharacterCasing = CharacterCasing.Upper;

It works more or less but it doesn't handle locales very well. For example in German language ß is SS when converted in upper case (Institut für Deutsche Sprache) and this property doesn't handle that.

You may mimic CharacterCasing property adding this code in KeyPress event handler:

e.KeyChar = Char.ToUpper(e.KeyChar);

Unfortunately .NET framework doesn't handle this properly and upper case of sharp s character is returned unchanged. An upper case version of ß exists and it's and it may create some confusion, for example a word containing "ss" and another word containing "ß" can't be distinguished if you convert in upper case using "SS"). Don't forget that:

However, in 2010 the use of the capital sharp s became mandatory in official documentation when writing geographical names in all-caps.

There isn't much you can do unless you add proper code for support this (and others) subtle bugs in .NET localization. Best advice I can give you is to use a custom dictionary per each culture you need to support.

Finally don't forget that this transformation may be confusing for your users: in Turkey, for example, there are two different versions of i upper case letter.

If text processing is important in your application you can solve many issues using specialized DLLs for each locale you support like Word Processors do.

What I usually do is to do not use standard .NET functions for strings when I have to deal with culture specific issues (I keep them only for text in invariant culture). I create a Unicode class with static methods for everything I need (character counting, conversions, comparison) and many specialized derived classes for each supported language. At run-time that static methods will user current thread culture name to pick proper implementation from a dictionary and to delegate work to that. A skeleton may be something like this:

abstract class Unicode
{
    public static string ToUpper(string text)
    {
        return GetConcreteClass().ToUpperCore(text);
    }

    protected virtual string ToUpperCore(string text)
    {
        // Default implementation, overridden in derived classes if needed
        return text.ToUpper();
    }

    private Dictionary<string, Unicode> _implementations;

    private Unicode GetConcreteClass()
    {
        string cultureName = Thread.Current.CurrentCulture.Name;

        // Check if concrete class has been loaded and put in dictionary
        ...

        return _implementations[cultureName];
    }
}

I'll then have an implementation specific for German language:

sealed class German : Unicode
{
    protected override string ToUpperCore(string text)
    {
        // Very naive implementation, just to provide an example
        return text.ToUpper().Replace("ß", "ẞ");
    }
}

True implementation may be pretty more complicate (not all OSes supports upper case ẞ) but take as a proof of concept. See also this post for other details about Unicode issues on .NET.

Opsonin answered 3/5, 2014 at 13:7 Comment(2)
Sir, I am using WEB PROJECT... Can you suggest me solution for for Web projectVinny
@MUKESHBAFNA If it's ASP.NET stuff then things may change a lot! Anyway, updated answer to reflect this.Opsonin
R
1

if you can use LinqToObjects in your Project

private YourTextBox_TextChanged ( object sender, EventArgs e)
{
   return YourTextBox.Text.Where(c=> c.ToUpper());
}

An if you can't use LINQ (e.g. your project's target FW is .NET Framework 2.0) then

private YourTextBox_TextChanged ( object sender, EventArgs e)
{
   YourTextBox.Text = YourTextBox.Text.ToUpper();
}

Why Text_Changed Event ?

There are few user input events in framework..

1-) OnKeyPressed fires (starts to work) when user presses to a key from keyboard after the key pressed and released

2-) OnKeyDown fires when user presses to a key from keyboard during key presses

3-) OnKeyUp fires when user presses to a key from keyboard and key start to release (user take up his finger from key)

As you see, All three are about keyboard event..So what about if the user copy and paste some data to the textbox?

if you use one of these keyboard events then your code work when and only user uses keyboard..in example if user uses a screen keyboard with mouse click or copy paste the data your code which implemented in keyboard events never fires (never start to work)

so, and Fortunately there is another option to work around : The Text Changed event..

Text Changed event don't care where the data comes from..Even can be a copy-paste, a touchscreen tap (like phones or tablets), a virtual keyboard, a screen keyboard with mouse-clicks (some bank operations use this to much more security, or may be your user would be a disabled person who can't press to a standard keyboard) or a code-injection ;) ..

No Matter !

Text Changed event just care about is there any changes with it's responsibility component area ( here, Your TextBox's Text area) or not..

If there is any change occurs, then your code which implemented under Text changed event works..

Reparation answered 3/5, 2014 at 18:39 Comment(13)
LINQ is pretty useless in this case, no reason to be preferred over String.ToUpper() and it'll even add more trouble about encoding (UTF-16). That said good catch about paste operations (or drag & drop) but changing Text property will change caret position too (so user can't type in the middle of existing text), this must be handled with SelectionStart. Finally as Steve's solution this doesn't handle German text properly (it's just a framework bug but that's what we have).Opsonin
@Adriano LINQ is a little bit faster than standard e.Keychar() key handle method chunks..And more readable..I suggested for this reason..Yes UTF-16 is a big pain itself :) but as much as i know UTF-8 has no trouble with these situations; cause UTF-8 developed for avoiding UTF-16 and 32 problems..so, if UTF-16 or 32 is not a necessary for the project, then OP can create a static encoding with UTF-8 then no need to think about problems as these..in one of my winforms project I solved caret-position problematic with checking text length and actual caret position in text-area ;)Reparation
IMO LINQ is seldom faster than specialized code (but I agree here performance doesn't matter so to be readable is more important). OP must care about UTF-16 because it's how .NET strings are encoded: each System.Char is 16 bit (64K values), UNICODE characters are more than 1 milion. .NET strings are encoded in UTF-16. About caret yes: that's just what it should be done (save/restore SelectionStart property) but this doesn't work smoothly when length of lower-case and upper-case text are different (yes, they can be).Opsonin
@Adriano and as i am a Turkish guy, thank you to have knowledge of my language; +1 to you:) BTW, in Turkish language there is not only 2 big "i" letter..in our alphabet 2 different letters "i" and "ı" and their capitals with same order as above written "İ" and "I"..When you need Turkish-Lang don't waste your time..if you use standard latin letter "i" and capital of it "I" no problem for Turkish people, they can easily guess/understand the right word with the coming of whole sentence..Also the same for between "S-s" and "Ş-ş"; "U-u" and "Ü-ü"; "O-o" and "Ö-ö"; "C-c" and "Ç-ç"; "G-g" and "Ğ-ğ"Reparation
@Adriano yes .net and windows uses UTF-16 in memory but also supports natively UTF-8 as it is transformation and persistence standard (i.e. internet).. And as i said that .NEt FW supports utf-8 natively, Op can use UTF-8 encoding without any performance costs and could avoid problems of transferring the data even between processes..About caret: No i didnt use Selection in my project..i just did first pos to a variable and set the caret's position = ++variable when Text area is not null and ++variable != Text.Length ;) This was enough tricky for my needs in that projectReparation
I knew about ASCII "i" upper cased to "İ" instead of what may expect "I" because of a bug many years ago in a naive toupper() function. Anyway thank you to share that information! It's what I usually dislike: "users have to guess/understand". IMO there shouldn't be a half support, if an application pretends to be "international" then it has to support locales in the right way without excuses and without extra effort by users. Sequences you posted open even more issues with string comparison and free text search. Moreover some of your characters can be a single code point or a combined charOpsonin
Yes, what I mean is: if in memory representation is UTF-16 (of course other encodings are supported) then we can't consider a System.Char as a grapheme (because it's not fixed length). In short it means that string length != number of characters and two strings with a different length can be compared as equal. Moreover even naive case conversion algorithms can fail, for more details about what I mean: #23370344. Plus we have to consider bugs in .NET itself (I remember TextInfo class was pretty buggy in .NET < 2.0)Opsonin
Oh BTW yes, for something like this I don't think OP will ever need to do something more than what you did about caret!Opsonin
@Adriano :) I guess we are on same opinion : if you do something, then do your best ! :) You are exactly right! thats the why Msdn warns about that (string / char comparisons ) always but there is no a real and naive solution for that.. But as i know - if i am wrong please correct me - UTF-8 can hold all language specific chars which is popular ( +300 millions of users around the world) in 2 byte representations..So if OP don't need some esperanto or swahili language support 2 byte representation can be enough..(CJK langs and arabic is 3 bytes as i know) Anyway OP should care UTF-16Reparation
Sir, I am using WEB PROJECT... Can you suggest me solution for for Web projectVinny
@Reparation any UTF-x (or UCS-x) encoding can handle full 100k UNICODE character set (so far). Well UTF8/UTF16 comparison has a long history full of trouble. I understand choice to use UTF16 in memory because it makes things more easy for half world (west) and the other half is aware of the problem and they'll be careful.Opsonin
With UTF8 everyone MUST be aware (but it has some pretty good features like synchronization). For disk and network IMO UTF8 is best because it's smaller (most cases). UTF-16 problem (IMO) is that...it made most of people unaware that it's just an encoding so there are thousands of bugged applications all around the world (and half of the world write with some characters outside the two bytes encoded characters of utf16!)Opsonin
For me text box shows as if it is recieving capital lettrs but it is showing small letters in alert.Interinsurance
L
1
**/*Css Class*/**
.upCase
{
    text-transform: uppercase;
}

<asp:TextBox ID="TextBox1" runat="server" Text="abc" Cssclass="upCase"></asp:TextBox>
Lukasz answered 15/12, 2018 at 9:0 Comment(0)
A
0

I use to do this thing (Code Behind) ASP.NET using VB.NET:

1) Turn AutoPostBack = True in properties of said Textbox

2) Code for Textbox (Event : TextChanged) Me.TextBox1.Text = Me.TextBox1.Text.ToUpper

3) Observation After entering the string variables in TextBox1, when user leaves TextBox1, AutoPostBack fires the code when Text was changed during "TextChanged" event.

Abroms answered 24/10, 2019 at 9:18 Comment(0)
D
0

I had the same problem with Visual Studio 2008 and solved adding the following event handler to the textbox:

        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        if ((e.KeyChar >= 'a') && (e.KeyChar <= 'z'))
        {
            int iPos = textBox1.SelectionStart;
            int iLen = textBox1.SelectionLength;
            textBox1.Text = textBox1.Text.Remove(iPos, iLen).Insert(iPos, Char.ToUpper(e.KeyChar).ToString());
            textBox1.SelectionStart = iPos + 1;
            e.Handled = true;
        }
    }

It works even if you type a lowercase character in a textbox where some characters are selected. I don't know if the code works with a Multiline textbox.

Desiderate answered 19/12, 2019 at 9:30 Comment(0)
H
-1

set your CssClass property in textbox1 to "cupper", then in page content create new css class :

<style type="text/css">.cupper {text-transform:uppercase;}</style>

Then, enjoy it ...

Hamilton answered 28/1, 2015 at 2:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.