Simplest way to perform data validation for fields on Windows Forms
Asked Answered
P

6

8

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.

Pastiche answered 23/11, 2012 at 11:29 Comment(2)
When user clicks Calculate, you can check whether the required fields contain required values in expected ranges. If not you can "Show" message accordingly, instructing the user to enter correct values. I'll add a code sample in a minute.Lian
@Lian that is what i am doing right now! Was looking for some other way to do it. For instance, take the validation controls we have in ASP.Net. I feel the validation controls, since they are positioned right next to the input controls help the user immediately understand what he's doing wrong and thereby give him a better experience. Also no code is run, which saves unnecessary processsing timePastiche
B
14

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();
}
Bluepoint answered 27/1, 2014 at 12:34 Comment(0)
E
5

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.

Effendi answered 23/11, 2012 at 13:12 Comment(1)
I like this approach, I had a small form that needed some validation and went for this, simple to implement and maintain (for small forms)October
L
4

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.

Lian answered 23/11, 2012 at 12:8 Comment(3)
I wouldn't really recommend that, it's really annoying as a user to see that kind of validations. Let's suppose that you have a form with 5 textboxes, two comboboxes and three radiobuttons and I make a mistake on every single one of them, the validation will point out one mistake per time, are you really expecting your user to click Calculate_button until they have entered all the informacion correctly? I would rather place labels to warn him about all his mistakes at once.Arcboutant
That is a terrible, terrible form of validation. At very least, rather put all the errors in a list, and display that list after validation. I can't imagine how I would hate using your software if I was new, made errors, and then had to close ten million message boxes.Sabotage
@Sabotage Upvoted... i0.kym-cdn.com/photos/images/newsfeed/000/096/044/…October
F
0

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
Forgiveness answered 23/11, 2012 at 11:53 Comment(1)
Re:Arek's comment (as I can't comment there yet). I agree that comments that pop up when you can't leave or have to click may be annoying so it is better to colour stuff or make a list of errors which is displayed after user clicks a button or add a label (show it) as Arek's suggested.Forgiveness
T
0

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

Typical answered 14/9, 2019 at 9:28 Comment(0)
S
-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
Stunt answered 16/12, 2013 at 15:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.