2

I use below code to not allowing any character except numbers in a textbox ... but it allows '.' character! I don't want it to allow dot.

    private void txtJustNumber_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (!char.IsDigit((char)(e.KeyChar)) &&
            e.KeyChar != ((char)(Keys.Enter)) &&
            e.KeyChar != (char)(Keys.Delete) &&
            e.KeyChar != (char)(Keys.Back)&&
            e.KeyChar !=(char)(Keys.OemPeriod))
        {
            e.Handled = true;
        }
    }
BenMorel
  • 34,448
  • 50
  • 182
  • 322
mjyazdani
  • 2,110
  • 6
  • 33
  • 64
  • take a look at [this thread](http://stackoverflow.com/questions/463299/how-do-i-make-a-textbox-that-only-accepts-numbers) – default Oct 25 '12 at 19:07

4 Answers4

3

use this:

    if (!char.IsDigit((char)(e.KeyChar)) &&
            e.KeyChar != ((char)(Keys.Enter)) &&
            (e.KeyChar != (char)(Keys.Delete) || e.KeyChar == Char.Parse(".")) &&
            e.KeyChar != (char)(Keys.Back) 
            )

it is because Keys.Delete's char value is 46 which is the same as '.'. I do not know why it likes this.

urlreader
  • 6,319
  • 7
  • 57
  • 91
0

You could try this instead (where textBox1 would be your textbox):

// Hook up the text changed event.
textBox1.TextChanged += textBox1_TextChanged;

...

private void textBox1_TextChanged(object sender, EventArgs e)
{
    // Replace all non-digit char's with empty string.
    textBox1.Text = Regex.Replace(textBox1.Text, @"[^\d]", "");
}

Or

// Save the regular expression object globally (so it won't be created every time the text is changed).
Regex reg = new Regex(@"[^\d]");

private void textBox1_TextChanged(object sender, EventArgs e)
{
    if (reg.IsMatch(textBox1.Text))
        textBox1.Text = reg.Replace(textBox1.Text, ""); // Replace only if it matches.
}
Mario S
  • 11,715
  • 24
  • 39
  • 47
0
//This is the shortest way
private void txtJustNumber_KeyPress(object sender, KeyPressEventArgs e)
{
    if(!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
    {
        e.Handled = true; 
    }
}
0

try this code for your problem in keypress event :

   private void txtMazaneh_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (!char.IsDigit(e.KeyChar) && (int)e.KeyChar != 8 ||(e.KeyChar= .))
            e.Handled = true;
    }
Ashkan
  • 1