Click here to Skip to main content
15,029,128 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I need to check whether user entered a character or numeric digit in DataGridViewTextBoxCell. How to perform this comparison on the basis of ASCII values of entered key in KeyPress Event of DataGridView.
Any Suggestion ?
AmitGajjar 20-Sep-12 3:57am
ok so what you have done so far ?
Itz.Irshad 20-Sep-12 4:00am
I've tried to achieve the same thing via Regex in CurrentCellDirtyStateChanged Event. It check only first entered character and perform validation accordingly but, when user enters 2nd character or 3rd and so forth.... it didn't work accordingly. I need to check it for every key press in that specif DataGridViewTextBoxCell.

There is an example in the documentation[^].
I mostly used this code snippet to validate textbox user input. But I think you can use it on a DataGridViewCell as well. Give it a try.

And you don't have to use ASCII codes in C#. You can compare e.KeyChar to an integer which represents the ASCII value directly.

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
            //97 - 122 = Ascii codes for simple letters
            //65 - 90  = Ascii codes for capital letters
            //48 - 57  = Ascii codes for numbers

            if (e.KeyChar != 8)
                if (e.KeyChar < 48 | e.KeyChar > 57)
                    e.Handled = true;
Itz.Irshad 20-Sep-12 4:04am
Strings ? Do I need to specify some reference here ? If yes then which one ?
Isuru Nanayakkara 20-Sep-12 4:10am
sorry. my original code snippet was written in VB.NET and I converted it using a converter. That why it gave that error. Fixed it now. See the improved answer.
Itz.Irshad 20-Sep-12 4:12am
No Problem, I've added Microsoft.VisualBasic Assembly. It works fine. Thanks
Use one of the System.Char[^] methods to check what it is.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900