C# Numeric Only TextBox

Once in a while you find yourself needing to stop certain keypresses in a C# desktop application.  I've found the best way is to handle this in the keypress event of a text box.  This is some very small code that shows how to only allow numeric digits to be pressed.

private void textBox_KeyPress( object sender, KeyPressEventArgs e )
{
     e.Handled = !char.IsDigit( e.KeyChar );
}


Now if you want to allow other characters, like the decimal, etc you need to get a bit fancier.


private void textBox_KeyPress( object sender, KeyPressEventArgs e )
{
       if( char.IsDigit( e.KeyChar ) || 
           e.KeyChar == '.' )
       {
          e.Handled = false;
      }
      else
      {
          e.Handled = true;
      }
}

To allow more characters you just need to modify that first if parameter to your needs.

Comments

Popular Posts