【问题标题】:Simplest way to perform data validation for fields on Windows Forms对 Windows 窗体上的字段执行数据验证的最简单方法
【发布时间】:2012-11-11 18:21:40
【问题描述】:

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

【问题讨论】:

  • 当用户点击计算时,您可以检查必填字段是否包含预期范围内的必填值。如果没有,您可以相应地“显示”消息,指示用户输入正确的值。我会在一分钟内添加一个代码示例。
  • @CRoshanLG 这就是我现在正在做的事情!正在寻找其他方法来做到这一点。例如,以我们在 ASP.Net 中的验证控件为例。我觉得验证控件,因为它们位于输入控件旁边,可以帮助用户立即了解他做错了什么,从而给他更好的体验。也不运行任何代码,节省了不必要的处理时间

标签: c# .net winforms validation .net-3.5


【解决方案1】:

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

How to: Display Error Icons for Form Validation 提供简短介绍。

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

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

【讨论】:

    【解决方案2】:

    我想实现所有自定义验证的最简单方法是在按钮单击事件中设置一组 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...
        }
    }
    

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

    【讨论】:

    • 我真的不建议这样做,作为用户看到这种验证真的很烦人。假设您有一个包含 5 个文本框、两个组合框和三个单选按钮的表单,并且我在每一个上都犯了一个错误,验证每次都会指出一个错误,您是否真的希望您的用户单击 Calculate_button 直到他们有正确输入所有信息?我宁愿贴上标签,一次性警告他所有的错误。
    • 这是一种可怕的、可怕的验证形式。至少,宁愿将所有错误放在一个列表中,并在验证后显示该列表。我无法想象如果我是新手,犯了错误,然后不得不关闭一千万个消息框,我会多么讨厌使用你的软件。
    【解决方案3】:

    你可以试试这个:

    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;
            }
        }
    }
    

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

    【讨论】:

    • 我喜欢这种方法,我有一个需要一些验证的小表单,并且实现了这个,易于实现和维护(对于小表单)
    【解决方案4】:

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

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

    【讨论】:

    • Re:Arek 的评论(因为我还不能评论)。我同意当您无法离开或必须单击时弹出的 cmets 可能很烦人,因此最好为内容着色或制作错误列表,在用户单击按钮或添加标签(显示)后显示为Arek 的建议。
    【解决方案5】:

    我知道这是一个旧线程。

    但我认为值得回答。

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

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

    并将验证功能添加到您的

    编辑

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

    【讨论】:

      【解决方案6】:
      '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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-11
        • 1970-01-01
        • 2016-05-10
        • 1970-01-01
        • 2021-03-19
        相关资源
        最近更新 更多