TextBox输入验证,仅限数字



您好。我对此感到很难过。TextBox1应该只接受数字,如果用户输入文本,将弹出一个消息框,说明只能输入数字。

我不知道该怎么做,因为消息框应该在不点击任何按钮的情况下弹出。

用户只需真正输入数字,如果输入非数字值,消息框就会立即出现。

这可能吗?

我已经尝试过KeyPress事件,但我仍然可以输入字母。请帮忙。

这是一个非常标准的实现,只是包含了一个对话框。通常情况下,对话框只会惹恼用户并将焦点从表单上移开,它会打断用户交互的流程,因此我们尽量避免它,但您可以调整MS Docs-KeyEventHandler Delegate文档中列出的标准示例:

// Boolean flag used to determine when a character other than a number is entered.
private bool nonNumberEntered = false;
// Handle the KeyDown event to determine the type of character entered into the control.
private void textBox1_KeyDown(object sender, System.Windows.Forms.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)
{
// A non-numerical keystroke was pressed.
// Set the flag to true and evaluate in KeyPress event.
nonNumberEntered = true;
}
}
}
//If shift key was pressed, it's not a number.
if (Control.ModifierKeys == Keys.Shift) {
nonNumberEntered = true;
}
}
private void textBox1_KeyPress(object sender, System.Windows.Forms.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;
MessageBox.Show("Only numeric input is accepted");
}
}

以这种方式使用KeyEventArgs可以访问被按下的原始物理键,并单独防止文本框接受按键。

当第三方控件(或您自己的代码(覆盖了标准实现时,这种类型的代码非常有用。然而,可以在KeyPress事件处理程序中完成所有操作:

private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
// Check for the flag being set in the KeyDown event.
if (!Char.IsNumber(e.KeyChar) && e.KeyChar != '.')
{
// Stop the character from being entered into the control since it is non-numerical.
e.Handled = true;
MessageBox.Show("Only numeric input is accepted");
}
}

但这仍然可以让我们输入一个值"0";12.333…44.5";因此,一个更完整的例子应该扩展前面的一个例子,并与文本框中的当前值进行比较:

private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
// Check for the flag being set in the KeyDown event.
bool isNumber = Char.IsNumber(e.KeyChar);
if (e.KeyChar == '.')
{
isNumber = !(sender as TextBox).Text.Contains(".");
}
if (!isNumber)
{
// Stop the character from being entered into the control since it is non-numerical.
e.Handled = true;
MessageBox.Show("Only numeric input is accepted");
}
}

相关内容

  • 没有找到相关文章

最新更新