How to force a textbox to accept only numbers in windows forms?

Some occasions we need to force a textbox to accept only numbers, that the user can’t key letters and with this add validation in user interface.

The following code forces the user to only key a number, you shall click in the control and click in KeyPress and add the next code:

private void MiTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
         if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) )
         {
             e.Handled = true;
         }
}

If you want force decimal numbers then you add the next code:

private void MiTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
          if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && (e.KeyChar != '.'))
          {
                e.Handled = true;
          }
 
            // solo 1 punto decimal
            if ((e.KeyChar == '.') && ((sender as TextBox).Text.IndexOf('.') > -1))
          {
                e.Handled = true;
          }
}

About

View all posts by