I am trying to prevent a user from entering anything into a particular textbox aside from a number or a period in C#. The textbox is supposed to contain an IP address. I have it working such that non-numeric entries are prevented, however I can't seem to get it to allow a period to be entered. How might I accomplish this?
private void TargetIP_KeyDown(object sender, KeyEventArgs e)
{
// Initialize the flag to false.
nonNumberEntered = false;
// Determine whether the keystroke is a number from the top of the keyboard.
if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9)
{
// Determine whether the keystroke is a number from the keypad.
if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9)
{
// Determine whether the keystroke is a backspace.
if (e.KeyCode != Keys.Back)
{
nonNumberEntered = true;
errorProvider1.SetError(TargetIP, FieldValidationNumbersOnly);
// A non-numerical keystroke was pressed.
// Set the flag to true and evaluate in KeyPress event.
}
}
}
//If shift key was pressed, it's not a number.
if (Control.ModifierKeys == Keys.Shift)
{
nonNumberEntered = true;
}
}
private void TargetIP_KeyPress(object sender, KeyPressEventArgs e)
{
// Check for the flag being set in the KeyDown event.
if (nonNumberEntered == true)
{
// Stop the character from being entered into the control since it is non-numerical.
e.Handled = true;
}
else
{
errorProvider1.Clear();
}
}