Using the KeyPress Event
private void NumericOnlyKeyBox_KeyPress(object sender, KeyPressEventArgs e) { var validKeys = new[] { Keys.Back, Keys.D0, Keys.D1 }; e.Handled = !validKeys.Contains((Keys)e.KeyChar); }
Setting e.Handled to true / false indicates whether the character should be accepted in the field or not.
You can learn more about KeyPressEventArgs on MSDN.
Note
Keys.Delete should span the keys Keys.Delete, Keys.Backspace and other back buttons.
Filip Ekberg
source share