Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1178
  • Last Modified:

How to enforce only uppercase letters in a textbox input in Visual C Sharp

I have a textbox in a form and I want to ensure that only upper case alphabets are entered into it,  i.e. A..Z. No other characters are allowed. How to do I ensure it in Visual C Sharp using the Keypress event, e.g.

System.Windows.Forms.KeyPressEventArgs e)
        {
            if(e.KeyChar ... && e.KeyChar) <---- Not sure what to put here
            {
                e.Handled = true;
            }

I thought of using the range of Ascii values of A to Z, i.e. 65 to Z 91 to do this, but am not sure how to obtain the Ascii value in Visual C#.

0
geeta_m9
Asked:
geeta_m9
  • 5
  • 4
  • 2
  • +1
2 Solutions
 
CuteBugCommented:
In the Properties dialog of the textbox, you can set the TextBox.CharacterCasing to Upper.

This way only upper characters will be entered in the text box.
0
 
angus_young_acdcCommented:
Or if you wished to do it programmatically (makes it easier to read controls properties instead of having to open the designer), you could create a textchanged event like so:

private void txtMyTextBox_TextChanged(object sender, EventArgs e)
        {
            txtMyTextBox.CharacterCasing = CharacterCasing.Upper;
        }

Or set the CharacterCasing within the forms initialisation.
0
 
angus_young_acdcCommented:
Should have said the reason you could create a custom event (obviously changing the name from txtMyTextBox) is that you can assign the event to all your textboxes on the form, or only specific ones, depending on your needs.
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
geeta_m9Author Commented:
I forgot to mention, I am using a rich textbox, not a regular textbox. I can't seem to be able to find that property there. Also, this doesn't prevent the user from entering other characters besides letters, i.e. the user could also enter numbers, punctuation, etc. I don't want the user to be able to do that...only enter letters.
0
 
CuteBugCommented:
Do the following-

Add a handler to the KeyPress event of the richtextbox
 richTextBox1.KeyPress += new KeyPressEventHandler(richTextBox1_KeyPress);
        
 
        void richTextBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (Char.IsLower(e.KeyChar))
            {
                richTextBox1.SelectedText = Char.ToUpper(e.KeyChar).ToString();
            }
            e.Handled = true;            
        }

Open in new window

0
 
geeta_m9Author Commented:
CuteBug, I tried your code, but it is still allowing me to enter other characters besides letters. I want to enforce it so that the user can only enter letters which will convert to uppercase and nothing else.
0
 
CuteBugCommented:
Hi geeta_m9,
        It is working fine here...

        It is only accepting letters.

regards
CuteBug
0
 
geeta_m9Author Commented:
Is there something else I need to include the code that you may have left out? For instance, do I need to add some code related to this to the form class? I created a separate class called the rich textbox class, and put the code that you gave me in there.
0
 
CuteBugCommented:
Sorry for the late reply.

You do not need to create a new class.

Here is what I did.
From the ToolBox I dragged and dropped the RichTextBox Ctrl onto the form.

Then in the events section of the RichTextBox Property Dialog, I added a handler to the KeyPress event.

Within the handler, I added the code which I poster earlier.

Now your RichTextBox will accept only Uppercase letters.
0
 
Todd GerbertIT ConsultantCommented:
CuteBug was close, but didn't take into account if the user enters an upper case letter to let it through, or spaces (which you may or may not want).

If you intend to do this frequently, you may want to consider creating a control with a Rich Text Box on it with this event handler (or inheriting from the Rich Text Box and extending it), this way you can just add an UpperCaseRichTextBox to your forms and be done with it, instead of connecting a bunch of event handlers.
        private void richTextBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            // If the keypress is a-z or A-Z...
            if ((e.KeyChar >= 'a' && e.KeyChar <= 'z') || (e.KeyChar >= 'A' && e.KeyChar <= 'Z') ||
                (e.KeyChar = ' '))
            {
                e.KeyChar = Char.ToUpper(e.KeyChar); // Then change the key pressed to upper case
                e.Handled = false; // Tell rich text box we didn't handle it here, the text box's logic will
            }
            else
                e.Handled = true; // If any other key, ignore it, tell the rich text box we took care of it but
                                    // actually, we didn't
        }
 
===================================================================================================
public partial class Form1 : Form
{
    private UpperCaseRichTextBox UCRichTextBox1;
    public Form1()
    {
        UCRichTextBox1 = new UpperCaseRichTextBox();
        UCRichTextBox1.SuspendLayout();
        UCRichTextBox1.Name = "UCRichTextBox1";
        UCRichTextBox1.Dock = DockStyle.Fill;
        UCRichTextBox1.ResumeLayout(false);
        this.Controls.Add(UCRichTextBox1);
 
        InitializeComponent();
    }
}
public class UpperCaseRichTextBox : RichTextBox
{
 
    protected override void OnKeyPress(KeyPressEventArgs e)
    {
        if ((e.KeyChar >= 'a' && e.KeyChar <= 'z') || (e.KeyChar >= 'A' && e.KeyChar <= 'Z') ||
            (e.KeyChar == ' '))
        {
            e.KeyChar = Char.ToUpper(e.KeyChar);
            e.Handled = false;
        }
        else
            e.Handled = true;
        base.OnKeyPress(e);
    }
}

Open in new window

0
 
CuteBugCommented:
Hi tgerbert,
       Thank you for pointing out the error in my code.

       I have updated my code to handle that scenario too.
private void richTextBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if ((Char.IsLower(e.KeyChar)) || (Char.IsUpper(e.KeyChar)))
            {
                richTextBox1.SelectedText = Char.ToUpper(e.KeyChar).ToString();
            }
            e.Handled = true; 
        }

Open in new window

0
 
geeta_m9Author Commented:
So for taking so long to get back to you. I discovered that I wasn't putting the code in the correct control and that's why it wasn't working.
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 5
  • 4
  • 2
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now