Simplest way to perform data validation for fields on Windows Forms

試著忘記壹切 提交于 2021-02-07 13:42:00

问题


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 boxes and one combo box. So basically all these fields need to contain a value in order to perform the calculations. Additionally, the text boxes should contain numbers - any double values. Moreover, I want to set a maximum value set for most of these text boxes which 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.


回答1:


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 ErrorProvider which will facilitate us to show error on the required field.

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

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

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



回答2:


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

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.




回答3:


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.




回答4:


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

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.

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



回答5:


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




回答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


来源:https://stackoverflow.com/questions/13528175/simplest-way-to-perform-data-validation-for-fields-on-windows-forms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!