Simplest way to perform data validation for fields on Windows Forms

.net, .net-3.5, c#, validation, winforms

Solution

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

Problem

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.

Original source