在Windows Forms上执行数据验证的最简单方法

8
我有一个Windows表单项目,我想在用户按下底部的计算按钮之前强制用户输入某些字段中的值。这些字段包括三对单选按钮、五个文本框和一个组合框。因此,所有这些字段都需要包含一个值才能执行计算。此外,文本框应该包含数字-任何双精度值。此外,我希望为大多数文本框设置最大值,用户不能超过该值。请告诉我实现这一点的最简单方法。我没有看到类似于ASP.Net中可用的Winform项目的字段验证控件。请注意,我正在使用.net 3.5。目前,我使用消息框将此通知给用户,即每当用户按下计算时,我会显示消息框,其中提到当前为空的必填字段的名称。

当用户点击“计算”按钮时,您可以检查所需字段是否包含预期范围内的必要值。如果不是,则可以相应地“显示”消息,指示用户输入正确的值。我马上会添加一个代码示例。 - CRoshanLG
@CRoshanLG,这就是我现在正在做的事情!我正在寻找其他方法来完成它。例如,我们在ASP.Net中拥有的验证控件。我觉得验证控件由于它们紧贴输入控件而放置,可以帮助用户立即了解他做错了什么,从而为他提供更好的体验。此外,不需要运行任何代码,这可以节省不必要的处理时间。 - R.S.K
6个回答

14

我遇到了和你一样的情况,而且我找到了一个简单的解决方案,或者说可用于WinForms的简单解决方案。WinForms包含一个控件ErrorProvider,它将帮助我们在必填字段上显示错误。

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

ErrorProvider可以根据您的需要使用,例如对于文本框,您可以在TextChanged事件处理程序中使用它,或者在任何其他事件中使用它,比如按钮事件,像这样:

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

5
你可以尝试这样做:
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;
        }
    }
}

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


我喜欢这种方法,我有一个需要一些验证的小表单,就采用了这种方法,对于小表单来说实现和维护都很简单。 - Nelson

4
我猜实现所有自定义验证的最简单方式是在按钮点击事件内部具有一组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...
    }
}

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

9
我不太推荐那样做,作为用户看到那种验证方式真的很烦人。比如,假设你有一个包含5个文本框、两个组合框和三个单选按钮的表格,如果我每个都犯错,那么验证会一次提示一个错误,你真的希望用户点击“计算”按钮直到他们正确输入所有信息吗?相反,我宁愿添加标签,同时警告他们所有的错误。 - user1162766
2
那是一种非常糟糕的验证方式。至少应该将所有错误放在一个列表中,在验证后显示该列表。如果我是新手,犯了错误然后不得不关闭一百万个消息框,我无法想象我会多么讨厌使用你的软件。 - ProfK
1
@ProfK 点赞了... http://i0.kym-cdn.com/photos/images/newsfeed/000/096/044/trollface.jpg?1296494117 - Nelson

0

尝试使用控件的验证事件,并在其中编写所需的验证代码。

以下是一个示例,它使用一些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

回复:Arek的评论(因为我还不能在那里发表评论)。我同意,当你无法离开或必须点击时弹出的评论可能会很烦人,因此最好将内容着色或制作一个错误列表,在用户单击按钮后显示,或添加一个标签(显示它),就像Arek建议的那样。 - pkoszka

0

我知道这是一个旧的帖子。

但我认为它值得回答。

在计算按钮点击函数中添加

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

并为您的编辑功能添加验证函数

编辑

抱歉,此功能仅适用于.NET 4.0及以上版本


-2
'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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接