1
我試圖阻止用戶輸入任何東西到一個特定的文本框,除了在C#中的數字或句點。該文本框應該包含一個IP地址。我有它的工作,以防止非數字條目,但我似乎無法讓它進入一段時間。我該如何做到這一點?一個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的,但非常適用於語言無關且絕對適用):http://www.perlmonks.org/?node_id=221512 – rmeador 2009-04-28 18:31:34
此IP地址格式的字段驗證無需完美,只要它只能接受數字和小數點,而拒絕所有其他類型的輸入。 – 2009-04-28 18:41:53