C# 对 Windows 窗体上的字段执行数据验证的最简单方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13528175/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 08:55:01  来源:igfitidea点击:

Simplest way to perform data validation for fields on Windows Forms

c#.netwinformsvalidation.net-3.5

提问by R.S.K

I have a windows form project in which I want to force the user to enter values in certain fields before he presses the calculate button at the bottom. The fields include three pairs of radio buttons, five text boxesand one combo box. So basically all these fields need to contain a value in order to perform the calculations. Additionally, the text boxesshould contain numbers- any double values. Moreover, I want to set a maximumvalue set for most of these text boxeswhich the user cannot exceed. Please let me know what is the simplest way to achieve this. I don't see field validating controls for winform projects like those available in ASP.Net. Please note, I am working on .net 3.5. Currently, I am using the message boxes to communicate this to the user i.e. whenever the user does press calculate I display message boxes mentioning the name of the required fields which are presently empty.

我有一个 windows 窗体项目,我想强制用户在按下底部的计算按钮之前在某些字段中输入值。这些字段包括三对单选按钮、五个文本框和一个组合框。所以基本上所有这些字段都需要包含一个值才能执行计算。此外,文本框应包含数字- 任何双精度值。此外,我想为大多数这些文本框设置一个最大值用户不能超过。请让我知道实现这一目标的最简单方法是什么。我没有看到像 ASP.Net 中可用的 winform 项目的字段验证控件。请注意,我正在使用 .net 3.5。目前,我正在使用消息框将其传达给用户,即每当用户按下计算时,我都会显示消息框,其中提到了目前为空的必填字段的名称。

回答by pkoszka

Try using Validating event of the control and code whatever validation you need in there.

尝试使用控件的 Validating 事件并在其中编写您需要的任何验证。

Here is an example which uses some ValidateEmail function to check if the text is an e-mail address, sets the background to some (red?) colour if it doesn't match and doesn't let user to leave control until it matches.

这是一个示例,它使用一些 ValidateEmail 函数来检查文本是否是电子邮件地址,如果不匹配,则将背景设置为某种(红色?)颜色,并且在匹配之前不允许用户离开控制权。

Private Sub VoucherEmail_Validating(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles Textbox.Validating
    If Not ValidateEmail(sender.Text) Then
        sender.backcolour = Validation.ErrorBackgrounColor
        e.Cancel = True
    End If
End Sub

回答by CRoshanLG

I guess the easiest way to implement all your custom validation is to have a set of if conditions inside the button click event.

我想实现所有自定义验证的最简单方法是在按钮单击事件中设置一组 if 条件。

private void Calculate_button_Click(object sender, EventArgs e)
{
    if(textBox1.Text == string.Empty)
    {
        MessageBox.Show("Please enter a value to textBox1!");
        return;
    }
    else if(!radioButton1.Checked && !radioButton2.Checked)
    {
        MessageBox.Show("Please check one radio button!");
        return;
    }
    else if(comboBox1.SelectedIndex == -1)
    {
        MessageBox.Show("Please select a value from comboBox!");
        return;
    }
    else
    {
        // Program logic...
    }
}

In the same way you can check the ranges as well.

以同样的方式,您也可以检查范围。

回答by gabriel prakash

You can try this :

你可以试试这个:

private void Calculate_button_Click(object sender, EventArgs e)
{
    RadioButton[] newRadioButtons = { radiobutton1, radiobutton2, radiobutton3 };
    for (int inti = 0; inti < newRadioButtons.Length; inti++)
    {
        if (newRadioButton[inti].Checked == false)
        {
            MessageBox.Show("Please check the radio button");
            newRadioButtons[inti].Focus();
            return;
        }
    }
    TextBox[] newTextBox = { txtbox1, txtbox2, txtbox3, txtbox4, txtbox5 };
    for (int inti = 0; inti < newRadioButtons.Length; inti++)
    {
        if (newTextBox[inti].text == string.Empty)
        {
            MessageBox.Show("Please fill the text box");
            newTextBox[inti].Focus();
            return;
        }
    }
}

You can loop through the controls and find them whether they are filled or not if they are not filled it will show in message box and particular control will be focused.

您可以遍历控件并查找它们是否已填充,如果未填充,它将显示在消息框中,并且特定控件将被聚焦。

回答by BINU NARAYANAN NELLIYAMPATHI

'You can try this code----- 
'Function for null validate for particular type of controls in your form
Function NullValidate() As Boolean
    NullValidate = True
    For Each ctrl As Control In Me.Controls
        If TypeOf ctrl Is TextBox Then
            If ctrl.Text = "" Then
                MessageBox.Show("Invalid input for " & ctrl.Name)
                NullValidate = False
               Exit Function
            Else
               NullValidate = True
            End If
         End If
    Next
End Function
'Function for numeric validate for particular type of controls in your form
 Function NumericValidate() As Boolean
     NumericValidate = True
    For Each ctrl As Control In Me.Controls
         If TypeOf ctrl Is TextBox Then
             If NumericValidate = IsNumeric(ctrl.text) Then
                   MessageBox.Show("Invalid input for " & ctrl.Name)
                  NumericValidate = False
                  Exit Function
             Else
                  NumericValidate = True
             End If
         End If
     Next
   End Function

Private Sub cmdCalculate_Click(sender As Object, e As EventArgs) Handles cmdSave.Click
     If NullValidate() = True Then
         If NumericValidate() = True Then
             'your statement is here
         End If
     End If
End Sub

回答by Zeeshan Ajmal

I came across same situation as you, and I found an easy solution or you can say that easy solution available for WinForms. WinForms contains a control ErrorProviderwhich will facilitate us to show error on the required field.

我遇到了和你一样的情况,我找到了一个简单的解决方案,或者你可以说 WinForms 可用的简单解决方案。WinForms 包含一个控件ErrorProvider,可以方便我们在所需字段上显示错误。

The How to: Display Error Icons for Form Validationprovides a short introduction.

如何为表单验证显示错误图标提供了一个简短的介绍。

ErrorProvidercan be used the way you want to e.g. for a textbox you can use it in the TextChangedevent handler or inside any other let's say button's event, like so:

ErrorProvider可以按照您想要的方式使用,例如,对于文本框,您可以在TextChanged事件处理程序中或在任何其他让我们说按钮的事件中使用它,如下所示:

if (!int.TryParse(strNumber, out result))
{
    errorProvider.SetError(tbNumber, "Only Integers are allowed");
}
else
{
    errorProvider.Clear();
}

回答by haxpak

I Know this is an old thread.

我知道这是一个旧线程。

But I think its worth answering.

但我认为它值得回答。

In the calculate button click function add

在计算按钮点击功能中添加

if(!this.ValidateChildren())
            {
                return;
            }

and add validating functions to your

并将验证功能添加到您的

edit

编辑

Sorry this works on .NET 4.0 and above

抱歉,这适用于 .NET 4.0 及更高版本