验证TextBox中的文本更改

时间:2009-03-04 14:08:00

标签: c# .net winforms validation textbox

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

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

5 个答案:

答案 0 :(得分:5)

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

答案 1 :(得分:4)

TextChanged事件

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

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

答案 2 :(得分:1)

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

以下是来自MSDN documentation示例

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

答案 3 :(得分:1)

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

答案 4 :(得分:1)

将文本框绑定到bindingSource时,请转到“高级”并选择验证类型
“关于财产的变化”。这会在每次按键时将数据传播到您的实体。 的 Here is the screen shot