【发布时间】:2009-04-28 18:22:40
【问题描述】:
我试图阻止用户在 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.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();
}
}
【问题讨论】:
-
您知道 IP 地址可以采用多种形式,而不是您试图让用户输入的形式,对吧?如果没有,请尝试阅读这篇文章(它是关于 perl,但与语言无关,绝对适用):perlmonks.org/?node_id=221512
-
这种 IP 地址格式的字段验证不必是完美的,只要它只能接受数字和小数点,而拒绝所有其他类型的输入。
标签: c# winforms validation controls keyboard