【发布时间】:2010-10-11 06:37:09
【问题描述】:
我已经在我的 WinForm 中的文本框上实现了验证规则,它运行良好。但是,它仅在我退出该字段时检查验证。我希望它在框中输入任何内容以及每次内容更改时立即进行检查。我还希望它在 WinForm 打开后立即检查验证。
我记得最近通过设置一些事件和诸如此类的东西来做到这一点,但我似乎不记得是如何做到的。
【问题讨论】:
标签: c# .net winforms validation textbox
我已经在我的 WinForm 中的文本框上实现了验证规则,它运行良好。但是,它仅在我退出该字段时检查验证。我希望它在框中输入任何内容以及每次内容更改时立即进行检查。我还希望它在 WinForm 打开后立即检查验证。
我记得最近通过设置一些事件和诸如此类的东西来做到这一点,但我似乎不记得是如何做到的。
【问题讨论】:
标签: c# .net winforms validation textbox
如果您使用数据绑定,请转到文本框的属性。打开顶部的(DataBindings),点击(Advanced)属性,会出现三个点(...)点击那些。出现高级数据绑定屏幕。对于绑定的 TextBox 的每个属性,在您的情况下为 Text,您可以使用组合框 Data Source Update mode 设置数据绑定以及验证何时“启动”。如果您将其设置为OnPropertyChanged,它将在您键入时重新评估(默认为OnValidation,它只会在您选择时更新)。
【讨论】:
TextChanged 事件
以后您可以在 MSDN 库中找到所有事件,这里是 TextBox class reference:
http://msdn.microsoft.com/en-us/library/system.windows.forms.textbox(VS.80).aspx
【讨论】:
如果没有完成,您的数据将如何有效?即用户键入一个数字,您尝试将其验证为日期?
【讨论】:
将文本框绑定到 bindingSource 时,转到 Advanced 并选择验证类型
“关于属性改变”。这将在每次按键时将您的数据传播到您的实体。
Here is the screen shot
【讨论】:
您应该检查 KeyPress 或 KeyDown 事件,而不仅仅是您的 TextChanged 事件。
这是直接来自MSDN documentation 的 C# 示例:
// 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;
}
}
【讨论】: