且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

窗口形式验证

更新时间:2023-10-19 18:13:22

此论坛用于回答未提供教程的具体问题。



MS文档是***的起点

Windows窗体中的用户输入验证 [ ^ ]

Control.Validating事件(System.Windows.Forms) [ ^ ]



和这个博客解释了如何使用这两个事件 Windows窗体中的验证 [ ^ ]



如果你遇到了一个特定的问题,然后回来你的代码,我们将尝试帮助


假设 Control.CausesValidation Property(System.Windows.Forms) [ ^ ]设置为true :

验证事件发生在用户在离开事件之后立即离开控件时,如果验证失败,则允许您通过设置取消属性取消尝试离开提供了CancelEventArgs。你将Cancel设置为true,焦点不会离开控件。

Validated事件在Validating事件发生后立即发生 - 只要它没有设置Cancel属性 - 并允许你工作使用经过验证的数据。

 私人  void  tbSolution_Validating( object  sender,System.ComponentModel.CancelEventArgs e)
{
TextBox tb = sender as TextBox;
if (tb!= null
{
e。取消=!tb.Text.StartsWith( A);
}
}

私有 void tbSolution_Validated( object sender,EventArgs e)
{
TextBox tb = sender as TextBox;
if (tb!= null
{
Console。 WriteLine( {0}没问题!,tb.Text);
}
}



只有以字母'A'开头


i have a window form in .net framework.there are some textboxes and comboboxes. and checkboxes . i want to use validations in there controls . please send me some examples for help

What I have tried:

how to use validated and validating events

This forum is for answering specific questions not giving tutorials.

The MS documentation is the best place to start
User Input Validation in Windows Forms[^]
Control.Validating Event (System.Windows.Forms)[^]

and this blog explains how to use both events Validation in Windows Forms[^]

If you hit a specific problem then do come back with your code and we will try to help


Assuming the Control.CausesValidation Property (System.Windows.Forms)[^] is set to true:
The Validating event happens when the user tries to move away from a control, immediately after the Leave event, and allows you to cancel the attempt to leave if your validation fails by setting the Cancel property of the supplied CancelEventArgs. It you set Cancel to true, the focus will not move away from the control.
The Validated event happens immediately after the Validating event - provided it doesn't set the Cancel property - and allows you to work with the validated data.
private void tbSolution_Validating(object sender, System.ComponentModel.CancelEventArgs e)
    {
    TextBox tb = sender as TextBox;
    if (tb != null)
        {
        e.Cancel = !tb.Text.StartsWith("A");
        }
    }

private void tbSolution_Validated(object sender, EventArgs e)
    {
    TextBox tb = sender as TextBox;
    if (tb != null)
        {
        Console.WriteLine("{0} is OK!", tb.Text);
        }
    }


The text will only be printed provided it starts with the letter 'A'