Share via


How do make the texbox accept only numerics, del key and backspace?

Question

Sunday, September 1, 2013 3:39 AM | 1 vote

hi friends,

is there away to make a textbox accept only numeric, del key and backspace key?

I used the following code but it doesn't work:

        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if ( char.IsDigit(e.KeyChar) == true || e.KeyChar == Convert.ToChar(Keys.Back) || e.KeyChar == Convert.ToChar(Keys.Delete) )
            {
                e.Handled = true;
            }
        }

thanks

I use Visual studio 2010 professional and SQL server 2008 developer edition!

All replies (12)

Sunday, September 1, 2013 4:22 AM ✅Answered

numeric check keypress event

http://msdn.microsoft.com/en-us/library/ms171538.aspx

ASCII Key codes

http://help.adobe.com/en_US/AS2LCR/Flash_10.0/help.html?content=00000520.html


Sunday, September 1, 2013 4:31 AM ✅Answered

public partial class Form1 : Form
    {
        /// <summary>
        /// Whether Del is pressed or not
        /// </summary>
        private bool isDelPressed = false;
 
        public Form1()
        {
            InitializeComponent();
        }
 
        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            int n = (int)e.KeyChar;
            e.Handled = !(n == 8 || (n >= 48 && n <= 57) || isDelPressed);
        }
 
        private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            isDelPressed = (e.KeyCode == Keys.Delete);
        }
    }

If you think one reply solves your problem, please mark it as An Answer, if you think someone's reply helps you, please mark it as a Proposed Answer

Help by clicking:
Click here to donate your rice to the poor
Click to Donate
Click to feed Dogs & Cats

Found any spamming-senders? Please report at: Spam Report


Sunday, September 1, 2013 5:36 AM

I always prefer to do it via client side Javascript... It is faster than using code behind

<asp:TextBox ID="txtNumber" runat="server" onkeypress="AllowNumeric();" MaxLength="8"></asp:TextBox>

Choose the Javascript you prefer.

function isNumber(n) {  return !isNaN(parseFloat(n)) && isFinite(n);}function AllowNumeric() {  if ((event.keyCode > 47 && event.keyCode < 58) || (event.keyCode == 46) || (event.keyCode == 45)) {    event.returnValue = true;  }  else {    event.returnValue = false;  }}

Sunday, September 1, 2013 5:37 AM

PaulDAndrea;)

Maybe the problem of Windows Form instead of Web Form;)

If you think one reply solves your problem, please mark it as An Answer, if you think someone's reply helps you, please mark it as a Proposed Answer

Help by clicking:
Click here to donate your rice to the poor
Click to Donate
Click to feed Dogs & Cats

Found any spamming-senders? Please report at: Spam Report


Sunday, September 1, 2013 5:52 AM

True, the OP doesn't specify whether it is for a Windows Form or a Web Form... I made the assumed Web Form because he said his code behind example didn't work and with a Web Form using code behind for that would be tricky...

BTW here is a really ugly Javascript AllowNumeric I created a long time ago and haven't had time since to make it nice.  A lot of nested if's

function allowNumeric(textElement, AllowNegNum, LeftDigits, RightDigits) {  var caretPos = getCursorPos(textElement);  var numValue = textElement.value;  var decimalPos = numValue.indexOf('.');  var negPresent = numValue.indexOf('-');  if (AllowNegNum != true) AllowNegNum = false;    if (AllowNegNum) {      //Allows negative numbers.      if ((event.keyCode > 47 && event.keyCode < 58) || (event.keyCode == 46) || (event.keyCode == 45)) {      //Allow minus sign only in first position      if ((caretPos == 0) && (event.keyCode == 45)) {        event.returnValue = true;      }      else if ((caretPos == 0) && (event.keyCode != 45)) {        event.returnValue = true;      }      else if ((caretPos != 0) && (event.keyCode != 45)) {        event.returnValue = true;      }      else {        event.returnValue = false;     }      //One decimal point allowed      if ((event.keyCode) == 46 && (decimalPos > -1)) {        event.returnValue = false;      }    }    else {      event.returnValue = false;    }  }  else {    //Disallows negative numbers.    if ((event.keyCode > 47 && event.keyCode < 58) || (event.keyCode == 46)) {      event.returnValue = true;    }    else {      event.returnValue = false;    }    //One decimal point allowed    if ((event.keyCode) == 46 && (decimalPos > -1)) {      event.returnValue = false;    }  }  addValue = 0;  if (negPresent > -1) {    addValue = 1;  }  if (event.keyCode > 47 && event.keyCode < 58) {    //alert('in decimal check');    var decimalSplit = numValue.split('.');    if (decimalSplit[0].length < (LeftDigits + addValue)) {      event.returnValue = true;    }    else {      event.returnValue = false;    }    if (decimalSplit.length == 2) {      if (decimalSplit[1].length < RightDigits) {        event.returnValue = true;      }      else {        event.returnValue = false;      }      if (decimalSplit[0].length < (LeftDigits + addValue) && (decimalSplit[1].length == RightDigits)) {        if (caretPos <= decimalPos) {          event.returnValue = true;        }        else {          event.returnValue = false;        }      }    }  }}

Sunday, September 1, 2013 6:22 AM

Paul;)

Hahaha……TextBox in the WebForm doesn't have such events like Key_Press.....

Sniff_bits;)

Please confirm

If you think one reply solves your problem, please mark it as An Answer, if you think someone's reply helps you, please mark it as a Proposed Answer

Help by clicking:
Click here to donate your rice to the poor
Click to Donate
Click to feed Dogs & Cats

Found any spamming-senders? Please report at: Spam Report


Tuesday, September 3, 2013 1:46 AM

On the contrary my friend.  I actually have a few working web applications that does use keypress and it works just fine. The following is one of the more elabarate uses in a textbox I have

<asp:TextBox ID="control_Hours" runat="server" Width="50px" onkeypress="APPJS.allowNumeric(this, false, 2, 2);" onkeyup="APPJS.checkLimit(this, '24');" onblur="APPJS.setMaskUnderScoreZero();"></asp:TextBox>

The class and inheritance of the page

public partial class PageName : System.Web.UI.Page{.................}

Tuesday, September 3, 2013 2:00 AM

It doesn't show in the intellisence... I actually have a working web application that does us key_press and it works just fine.

Hi again;)

Do you mean TextBox control of Web has Key_Pressed event at server-side or client side?

If you think one reply solves your problem, please mark it as An Answer, if you think someone's reply helps you, please mark it as a Proposed Answer

Help by clicking:
Click here to donate your rice to the poor
Click to Donate
Click to feed Dogs & Cats

Found any spamming-senders? Please report at: Spam Report


Tuesday, September 3, 2013 2:29 AM

ProgrammingVolunteer ... I like that name BTW

I actually edited the post you quoted to clarify... And actually my intellisense shows it; so the part "It doesn't show in the intellisence..." was incorrect on my part.

It is all happening on the client side regarding the code I posted... There probably is a code behind way to do it even if you need to define the event handler your self... but alas I haven't needed to do that in the scenerios I've done this.


Tuesday, September 3, 2013 2:44 AM

Hahah……

Nothing special but just I wonder since the user is using Server side……

Waiting for user to response us;)

If you think one reply solves your problem, please mark it as An Answer, if you think someone's reply helps you, please mark it as a Proposed Answer

Help by clicking:
Click here to donate your rice to the poor
Click to Donate
Click to feed Dogs & Cats

Found any spamming-senders? Please report at: Spam Report


Tuesday, September 3, 2013 3:20 AM

This is THE WRONG FORUM for webforms. Cant you people read? This is a .net forum.

Renee

"MODERN PROGRAMMING is deficient in elementary ways BECAUSE of problems INTRODUCED by MODERN PROGRAMMING." Me


Monday, October 19, 2015 2:43 PM

You did the mistake which is reverse of your need. You need to accept only numbers or delete or backspace but prevented when these keys will press. e.Handle = true which prevents the input.

Make your code like this.

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if ( !char.IsDigit(e.KeyChar) || e.KeyChar != Convert.ToChar(Keys.Back) || e.KeyChar != Convert.ToChar(Keys.Delete) )
            {
                e.Handled = true;
            }
        }Orprivate void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if ( !char.IsDigit(e.KeyChar) || e.KeyChar != Convert.ToChar(Keys.Back) || e.KeyChar != Convert.ToChar(Keys.Delete) )
            {
                e.Handled = false;
            }
        }