C#验证Winforms上文本框的输入 [英] C# Validating input for textbox on winforms
问题描述
我想先检查用户在文本框中写的内容,然后再将其保存到数据库中。做这个的最好方式是什么?我想我总是可以写一些if或try-catch块,但是我想知道是否有更好的方法。我已经阅读了有关验证事件的内容,但不确定如何使用它们。
说明
有很多方法可以验证TextBox。您可以在以后每次击键或 Validating
事件中执行此操作。
<$>如果TextBox失去焦点,则会触发c $ c> Validating 事件。例如,当用户单击另一个控件时。如果您设置的 e.Cancel = true
,则TextBox不会失去焦点。
MSDN-Control.Validating事件当您使用键盘(TAB,SHIFT + TAB等),调用Select或SelectNextControl方法或设置ContainerControl来更改焦点时。 ActiveControl属性为当前形式,焦点事件按以下顺序发生
Enter
GotFocus
离开
确认
确认
LostFocus
使用鼠标或调用Focus方法更改焦点时,焦点事件按以下顺序发生: / p>
输入
GotFocus
LostFocus
离开
验证
验证
示例验证事件
private void textBox1_Validating(对象发送者,CancelEventArgs e)
{
if(textBox1.Text!= something)
e.Cancel = true;
}
更新
您可以使用 ErrorProvider
来可视化您的TextBox无效。
检出在Windows窗体和C#中使用错误提供程序控件
更多信息
I want to check what the user is writing in a textbox before I save it in a database. What is the best way to do this? I guess I can always write some ifs or some try-catch blocks, but I was wondering if there's a better method. I've read something about Validating Events, but I am not sure how can I use them.
Description
There are many ways to validate your TextBox. You can do this on every keystroke, at a later time, or on the Validating
event.
The Validating
event gets fired if your TextBox looses focus. When the user clicks on a other Control, for example. If your set e.Cancel = true
the TextBox doesn't lose the focus.
MSDN - Control.Validating Event When you change the focus by using the keyboard (TAB, SHIFT+TAB, and so on), by calling the Select or SelectNextControl methods, or by setting the ContainerControl.ActiveControl property to the current form, focus events occur in the following order
Enter
GotFocus
Leave
Validating
Validated
LostFocus
When you change the focus by using the mouse or by calling the Focus method, focus events occur in the following order:
Enter
GotFocus
LostFocus
Leave
Validating
Validated
Sample Validating Event
private void textBox1_Validating(object sender, CancelEventArgs e)
{
if (textBox1.Text != "something")
e.Cancel = true;
}
Update
You can use the ErrorProvider
to visualize that your TextBox is not valid.
Check out Using Error Provider Control in Windows Forms and C#
More Information
- MSDN - Control.Validating Event
- MSDN - ErrorProvider Component (Windows Forms)
- Using Error Provider Control in Windows Forms and C#
这篇关于C#验证Winforms上文本框的输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!