作者:yuanyuan | 来源:互联网 | 2023-05-18 12:44
Iamtryingtopreventauserfromenteringanythingintoaparticulartextboxasidefromanumbero
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?
我试图阻止用户在C#中的数字或句点之外输入特定文本框中的任何内容。文本框应包含IP地址。我有它的工作,以防止非数字条目,但我似乎无法让它允许输入一个句号。我怎么能做到这一点?
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.D9)
{
// Determine whether the keystroke is a number from the keypad.
if (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();
}
}
1 个解决方案