我在WinForm中的textBox上实现了验证规则,效果很好。但是,只有当我跳出字段时,它才会检查验证。我希望只要在框中输入任何内容并且每次内容发生变化时都要检查。我还想在WinForm打开后立即检查验证。

我记得最近通过设置一些事件和诸如此类的东西来做这件事,但我似乎无法记住如何。

有帮助吗?

解决方案

TextChanged事件

将来你可以找到MSDN库上的所有事件,这里是 TextBox类引用

http:// msdn.microsoft.com/en-us/library/system.windows.forms.textbox(VS.80).aspx

其他提示

如果您正在使用数据绑定,请转到文本框的“属性”。打开(DataBindings)在顶部,单击(高级)属性,将出现三个点(...)单击这些。出现高级数据绑定屏幕。对于绑定的TextBox的每个属性,在您的情况下 Text ,您可以设置何时数据绑定以及验证应该“启动”。使用组合框数据源更新模式。如果将其设置为 OnPropertyChanged ,它将在您键入时重新进行评估(默认为 OnValidation ,只会在您选项卡时更新)。

如果数据没有完成,您的数据将如何有效?即用户键入数字并尝试将其验证为日期?

将文本框绑定到bindingSource时,请转到“高级”并选择验证类型
“On Property Changed”。这会在每次按键时将数据传播到您的实体。 这是屏幕截图

您应该检查KeyPress或KeyDown事件,而不仅仅是TextChanged事件。

以下是来自 MSDN文档

// 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;
    }
}

// This event occurs after the KeyDown event and can be used to prevent
// characters from entering the control.
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;
    }
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top