Limit TextBox entry

How do I prevent a user from being able to entry non-numeric text in a textbox Are there textbox classes available that only accept integer values

Answer this question

Limit TextBox entry

  • Yannis26

    You should have a look at the MaskedTextBox class where you can define a mask to be all numeric with the Mask property.



  • Glenn Burnside

    The simplest way to limit the input type, is to validate the input befour it is even shown, here I use: OnKeyPress

    Here is a one method to do it, there might be some simpler way out there:

    this.MyTextBox += new KeyPressEventHandler(OnlyNumbers);


    void OnlyNumbers(object sender, KeyPressEventArgs e)
    {
    if (Convert.ToInt32('0') <= Convert.ToInt32(e.KeyChar) && Convert.ToInt32(e.KeyChar) <= Convert.ToInt32('9'))
    e.Handled = false; //Allow
    else
    e.Handled = true; //Not allow
    }

    You would ofcourse have to add: backspace and so on.

    Like I said, I think there are more simpler way out there, like the above user seaid, use Masked TextBox :)



  • GimGif

    Hi

    I don't think there is a textBox to perfom what you what. The way I do it is to have a class that is going to validate all your textBoxes have a looksie at this class.

  • hotmailman

    Hi again

    this is little snippet that validates during the user input

  • Ahmed abd el hakim

    hi,

    you can use keypress event handler to achive that


    public partial class Form1 : Form

    {
    public Form1()
    {
    InitializeComponent();
    //event handlers

    this.textBox1.Leave += new System.EventHandler(this.textBox1_Leave);
    this.textBox1.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.textBox1_KeyPress);
    }
    private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
    //this to validate during data entry

    if (!char.IsNumber(e.KeyChar) && e.KeyChar != '.')
    {
    MessageBox.Show("plz enter numbers only");
    e.Handled =
    true;
    }
    }
    private void textBox1_Leave(object sender, EventArgs e)
    {
    //this to validate during user right click the textbox and hit past

    double value;
    bool result = double.TryParse(textBox1.Text,out value);
    if (!result)
    {
    MessageBox.Show("this is not numeric \n plz insert numeric value");
    textBox1.Focus();
    }
    }
    }


    hope this helps



  • Eze..

    Perfect. Thanks.

  • Limit TextBox entry