Click here to Skip to main content
11,492,291 members (63,349 online)
Rate this: bad
good
Please Sign up or sign in to vote.
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 ?
Posted 19-Sep-12 22:55pm
Comments
@AmitGajjar at 20-Sep-12 3:57am
   
ok so what you have done so far ?
Itz.Irshad at 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.
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

There is an example in the documentation[^].
  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

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;
                }
            }
        }
  Permalink  
v5
Comments
Itz.Irshad at 20-Sep-12 4:04am
   
Strings ? Do I need to specify some reference here ? If yes then which one ?
nK0de at 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 at 20-Sep-12 4:12am
   
No Problem, I've added Microsoft.VisualBasic Assembly. It works fine. Thanks
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 3

Use one of the System.Char[^] methods to check what it is.
  Permalink  

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

  Print Answers RSS
0 Sergey Alexandrovich Kryukov 404
1 Maciej Los 266
2 KarstenK 220
3 Sascha Lefèvre 215
4 CPallini 208
0 Sergey Alexandrovich Kryukov 9,943
1 OriginalGriff 8,610
2 Sascha Lefèvre 3,609
3 Maciej Los 3,372
4 Richard Deeming 2,440


Advertise | Privacy | Mobile
Web02 | 2.8.150520.1 | Last Updated 20 Sep 2012
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100