问题描述
我想先检查用户在文本框中写的内容,然后再将其保存到数据库中。做这个的最好方式是什么?我想我总是可以写一些if或try-catch块,但是我想知道是否有更好的方法。我已经阅读了有关验证事件的内容,但不确定如何使用它们。
说明
有很多方法可以验证TextBox。您可以在以后每次击键或 Validating
事件中执行此操作。
<$>如果TextBox失去焦点,则会触发c $ c> Validating 事件。例如,当用户单击另一个控件时。如果您设置的 e.Cancel = true
,则TextBox不会失去焦点。
示例验证事件
private void textBox1_Validating(对象发送者,CancelEventArgs e)
{
if(textBox1.Text!= something)
e.Cancel = true;
}
更新
您可以使用 ErrorProvider
来可视化您的TextBox无效。
检出
更多信息
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.
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上文本框的输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!