THE*_*TOR 1 c# keyboard validation controls winforms
我试图阻止用户在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();
}
}
Run Code Online (Sandbox Code Playgroud)
您应该使用MaskedTextBox控件而不是普通TextBox控件.然后只需将Mask属性设置为990\.990\.990\.990,即可完成.
UPDATE
虽然我建议使用MaskedTextBox,但我从来没有(在leat我不能记得)自己使用它.现在我只是尝试了......好吧,忘了我说的话.我认为这可能是一个简单的解决方案,但它也是一个无法使用的解决方案.
新的,更复杂的,但更好的建议和我通常做的方式.
使用四个文本框创建自定义控件,三个标签之间各有一个点.
分析输入.
将属性添加到用户控件,该控件返回输入的地址.
可以使proeprty写入并添加事件处理.
| 归档时间: |
|
| 查看次数: |
4240 次 |
| 最近记录: |