none
Allow only number no Letters? RRS feed

  • Question

  • Hi all,

    How do I make a question that only accepts numbers and not letters.

    For example.

    Enter your age:

    Twelve

    "Please enter your age in numeric form.

    I assume that this is done by some sort of if statement?

    Any help would be great.

    Cheers.

    Friday, November 26, 2010 12:08 PM

Answers

  • This should do the trick:

    PS: the code has no warnings, only does let youtype integers.

        bool bJumping;
        private void textBox1_TextChanged(object sender, EventArgs e)
        {
          if (!bJumping)
          {
            int intValue = 0;
            string strValue = textBox1.Text;
            if (!String.IsNullOrEmpty(strValue))
            {
              bool bChecking = int.TryParse(strValue, out intValue);
              if (!bChecking)
              {
                bJumping = true;
                textBox1.Text = strValue.Remove(strValue.Length - 1, 1);
                textBox1.SelectionStart = textBox1.Text.Length;
              }
            }
          }
          else
            bJumping = false;
        }

    Friday, November 26, 2010 12:26 PM
  • Example three gives a very clear way to handle this.

     

    http://msdn.microsoft.com/en-us/library/system.windows.forms.keyeventargs.aspx

     

     


    Devlin Liles
    Friday, November 26, 2010 1:21 PM
  • u can use the keypress event on u r textbox:

    private void txtAge_KeyPress(object sender, KeyPressEventArgs e)
            {
                if (char.IsDigit(e.KeyChar) || (int)e.KeyChar == 8) // second expression is for backspace
                    e.Handled = false;
                else
                    e.Handled = true;

            }


    Thanks, Srinivasa Rao Dhulipalla
    Mark As Answer if it helped you.
    Friday, November 26, 2010 1:41 PM
  • You can also use this method:

    try
          {
            if (!Char.IsDigit(e.KeyChar)) e.Handled = true;
    
            if (e.KeyChar == '\b') e.Handled = false; //allow Backspace
    
            if (e.KeyChar.Equals('-') && TxtBPrice.SelectionStart == 0) e.Handled = false; //allow negative number
    
            if (e.KeyChar.Equals('.') && TxtBPrice.Text.IndexOf(".") == -1) e.Handled = false; //allow single decimal point
    
            if (e.KeyChar == '\r') TxtBPrice.Focus(); //Enter key moves to next control
          }
          catch
          {
          }
    


    www.midnightprogramer.net
    Friday, November 26, 2010 2:17 PM
  • you can read the example in this tutorial which is the solution of your problem,

    http://msdn.microsoft.com/en-us/library/system.windows.forms.control.keypress.aspx

    i m typing here too,

    // Boolean flag used to determine when a character other than a number is entered.
            private bool nonNumberEntered = false;

            // Handle the KeyDown event to determine the type of character entered into the control.
            private void textBox1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
            {
                // Initialize the flag to false.
                nonNumberEntered = false;

                // Determine whether the keystroke is a number from the top of the keyboard.
                if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9)
                {
                    // Determine whether the keystroke is a number from the keypad.
                    if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9)
                    {
                        // Determine whether the keystroke is a backspace.
                        if(e.KeyCode != Keys.Back)
                        {
                            // A non-numerical keystroke was pressed.
                            // Set the flag to true and evaluate in KeyPress event.
                            nonNumberEntered = true;
                        }
                    }
                }
                //If shift key was pressed, it's not a number.
                if (Control.ModifierKeys == Keys.Shift) {
                    nonNumberEntered = true;
                }
            }

            // This event occurs after the KeyDown event and can be used to prevent
            // characters from entering the control.
            private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
            {
                // Check for the flag being set in the KeyDown event.
                if (nonNumberEntered == true)
                {
                    // Stop the character from being entered into the control since it is non-numerical.
                    e.Handled = true;
                }
            }

    or you can try this method too...

    private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
    if (Char.IsDigit(e.KeyChar) )
    { MessageBox.Show("only numbers are allowed");
    e.Handled = true; ;
    }
    }

    Friday, November 26, 2010 2:29 PM
  • Hello guys,

     

    Or you can always create a custom TextBox control which takes an enumeration of InputType in which you can specify what chars are accepted in the textbox, something like this:

      public class CustomTextBox : TextBox
      {
        public InputTypeEnum InputType { get; set; }
    
        protected override void OnKeyPress(KeyPressEventArgs e)
        {
          if (e.KeyChar != '\b')
          {
            switch (InputType)
            {
              case InputTypeEnum.Text:
                e.Handled = !Char.IsLetter(e.KeyChar);
                break;
              case InputTypeEnum.Numeric:
                e.Handled = !Char.IsDigit(e.KeyChar);
                break;
            }
          }
    
          base.OnKeyPress(e);
        }
      }
    
      public enum InputTypeEnum
      {
        Text,
        Numeric
      }
    
    Hope this helps, if you have any other questions or comments, please let me know,

    Best Regards,
    Emanuel Varga
    Telerik WinForms MVP


    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".
    Friday, November 26, 2010 4:59 PM
  • hi Alexander.

    following code is very simple & short solution :

    you only need for following block code that uses from KeyPress event of TextBox:

       private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
          if (e.KeyChar >= 48 && e.KeyChar <= 57)
            textBox1.Text += e.KeyChar;
    
          else if (e.KeyChar == 8 && textBox1.Text.Length > 0) // earse textBoxNumber with BackSpace key
            textBox1.Text = textBox1.Text.Remove(textBox1.Text.Length - 1);
    
          textBox1.SelectionStart = textBox1.Text.Length;
        }


    .Net adventurer

    If (a post answers your question) {please click " Mark As Answer" and "Mark as Helpful" on that post} 

    Friday, November 26, 2010 6:14 PM

All replies

  • This should do the trick:

    PS: the code has no warnings, only does let youtype integers.

        bool bJumping;
        private void textBox1_TextChanged(object sender, EventArgs e)
        {
          if (!bJumping)
          {
            int intValue = 0;
            string strValue = textBox1.Text;
            if (!String.IsNullOrEmpty(strValue))
            {
              bool bChecking = int.TryParse(strValue, out intValue);
              if (!bChecking)
              {
                bJumping = true;
                textBox1.Text = strValue.Remove(strValue.Length - 1, 1);
                textBox1.SelectionStart = textBox1.Text.Length;
              }
            }
          }
          else
            bJumping = false;
        }

    Friday, November 26, 2010 12:26 PM
  • Example three gives a very clear way to handle this.

     

    http://msdn.microsoft.com/en-us/library/system.windows.forms.keyeventargs.aspx

     

     


    Devlin Liles
    Friday, November 26, 2010 1:21 PM
  • u can use the keypress event on u r textbox:

    private void txtAge_KeyPress(object sender, KeyPressEventArgs e)
            {
                if (char.IsDigit(e.KeyChar) || (int)e.KeyChar == 8) // second expression is for backspace
                    e.Handled = false;
                else
                    e.Handled = true;

            }


    Thanks, Srinivasa Rao Dhulipalla
    Mark As Answer if it helped you.
    Friday, November 26, 2010 1:41 PM
  • You can also use this method:

    try
          {
            if (!Char.IsDigit(e.KeyChar)) e.Handled = true;
    
            if (e.KeyChar == '\b') e.Handled = false; //allow Backspace
    
            if (e.KeyChar.Equals('-') && TxtBPrice.SelectionStart == 0) e.Handled = false; //allow negative number
    
            if (e.KeyChar.Equals('.') && TxtBPrice.Text.IndexOf(".") == -1) e.Handled = false; //allow single decimal point
    
            if (e.KeyChar == '\r') TxtBPrice.Focus(); //Enter key moves to next control
          }
          catch
          {
          }
    


    www.midnightprogramer.net
    Friday, November 26, 2010 2:17 PM
  • you can read the example in this tutorial which is the solution of your problem,

    http://msdn.microsoft.com/en-us/library/system.windows.forms.control.keypress.aspx

    i m typing here too,

    // Boolean flag used to determine when a character other than a number is entered.
            private bool nonNumberEntered = false;

            // Handle the KeyDown event to determine the type of character entered into the control.
            private void textBox1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
            {
                // Initialize the flag to false.
                nonNumberEntered = false;

                // Determine whether the keystroke is a number from the top of the keyboard.
                if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9)
                {
                    // Determine whether the keystroke is a number from the keypad.
                    if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9)
                    {
                        // Determine whether the keystroke is a backspace.
                        if(e.KeyCode != Keys.Back)
                        {
                            // A non-numerical keystroke was pressed.
                            // Set the flag to true and evaluate in KeyPress event.
                            nonNumberEntered = true;
                        }
                    }
                }
                //If shift key was pressed, it's not a number.
                if (Control.ModifierKeys == Keys.Shift) {
                    nonNumberEntered = true;
                }
            }

            // This event occurs after the KeyDown event and can be used to prevent
            // characters from entering the control.
            private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
            {
                // Check for the flag being set in the KeyDown event.
                if (nonNumberEntered == true)
                {
                    // Stop the character from being entered into the control since it is non-numerical.
                    e.Handled = true;
                }
            }

    or you can try this method too...

    private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
    if (Char.IsDigit(e.KeyChar) )
    { MessageBox.Show("only numbers are allowed");
    e.Handled = true; ;
    }
    }

    Friday, November 26, 2010 2:29 PM
  • Hello guys,

     

    Or you can always create a custom TextBox control which takes an enumeration of InputType in which you can specify what chars are accepted in the textbox, something like this:

      public class CustomTextBox : TextBox
      {
        public InputTypeEnum InputType { get; set; }
    
        protected override void OnKeyPress(KeyPressEventArgs e)
        {
          if (e.KeyChar != '\b')
          {
            switch (InputType)
            {
              case InputTypeEnum.Text:
                e.Handled = !Char.IsLetter(e.KeyChar);
                break;
              case InputTypeEnum.Numeric:
                e.Handled = !Char.IsDigit(e.KeyChar);
                break;
            }
          }
    
          base.OnKeyPress(e);
        }
      }
    
      public enum InputTypeEnum
      {
        Text,
        Numeric
      }
    
    Hope this helps, if you have any other questions or comments, please let me know,

    Best Regards,
    Emanuel Varga
    Telerik WinForms MVP


    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".
    Friday, November 26, 2010 4:59 PM
  • hi Alexander.

    following code is very simple & short solution :

    you only need for following block code that uses from KeyPress event of TextBox:

       private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
          if (e.KeyChar >= 48 && e.KeyChar <= 57)
            textBox1.Text += e.KeyChar;
    
          else if (e.KeyChar == 8 && textBox1.Text.Length > 0) // earse textBoxNumber with BackSpace key
            textBox1.Text = textBox1.Text.Remove(textBox1.Text.Length - 1);
    
          textBox1.SelectionStart = textBox1.Text.Length;
        }


    .Net adventurer

    If (a post answers your question) {please click " Mark As Answer" and "Mark as Helpful" on that post} 

    Friday, November 26, 2010 6:14 PM
  • thanks a lot for your code
    Friday, March 25, 2011 5:18 PM