Winform UI Validation

WinForm UI Validation

In my own application I need to validate dimensions as they are typed in. The sequence I used is as follows

  1. The user selects or types then moves
    away from the control.
  2. The control loses focus and notifies
    the View sending it's ID and the
    entry text.
  3. The View checks what Shape Program
    (a class implementing a interface)
    created the Form and passes it the
    ID and entry text
  4. The Shape Program returns a
    response.
  5. If the Response is OK the View
    updates correct Entry of the Shape
    Class.
  6. If the Response is OK the View tells
    the Form through a Interface that it
    is OK to shift the focus to the next entry.
  7. If the Response is not OK, the View
    looks at the response and using the
    Form Interface tells the form what
    to do. This usually means the focus
    shifts back to the offending entry
    with a message displayed telling the
    user what happened.

The advantage of this approach that validation is centralized in one location for a given Shape Program. I don't have to go modify each control or even really worry about the different types of controls on the form. Way back when I designed the software I decided how the UI going to work for textboxes, listboxes, combo boxes, etc. Also different levels of severity is handled differently.

The View takes care of that instructing the Form what to do through the Interface. How it actually is implemented is handled by the Form itself in it's implementation of the Interface. The View doesn't care if the Form is displaying yellow for warning and red for error. Only that it handles those two levels. Later if a better idea of displaying warning vs errors comes along I can make the change in the Form itself rather mucking around with the View logic or the validate in Shape Program.

You are already halfway there if you are considering making a class to hold your validation logic this will get you the rest of the way in your new design.

Validating user input / Give .NET controls status OK or NOK

You have some useful facilities in windows forms to perform validation and show error messages including:

  • IDataErrorInfo Interface
  • Validating Event of Controls
  • ErrorProvider Component
  • ValidateChildren Method and AutoValidate Property of Form

Using above options:

  • You can perform validation when you are using data-binding to model classes.
  • You van perform validation when you don't use data-binding.
  • You can show error messages and an error icon near the controls which are in invalid states.
  • You can decide to prevent the focus change from invalid controls or let the focus change.
  • You can show a validation summary for your form.
  • You can also apply DataAnnotations Validations in Windows Forms

IDataErrorInfo Interface

In cases which you have some model classes, the best fit for validation and providing error messages in windows forms is implementing IDataErrorInfo. It's supported by data-binding mechanisms and some windows forms control like DataGridView and ErrorProvider.

To keep things simple you can write validation rules in your class and return error messages using IDataErrorInfo properties. Even if you want to apply a more advanced scenario like using validation engines, at last it's better to implement IDataErrorInfo to gain most consistency with widows forms.

You will use an ErrorProvider to show error messages. It's enough to bind it to your data source and it shows errors automatically.

Validating Event of Controls

In cases that you don't have model classes and all validations should be done against controls, the best option is using Validating event of controls. There you can set e.Cancel = true to set the control state as invalid. Then you can prevent focus change or use the state of control in getting validation summary.

In this case you will use an ErrorProvider to show errors. It's enough to set an error for a control in Validating event this way: errorProvider1.SetError(control1, "Some Error") or you can set an empty error message to remove validation error.

ErrorProvider Component
In both cases when you use databinding or when you use Validating event, as mentioned above, ErrorProvider shows and error icon with a tooltip that shows error message for you near the controls. (DataGridView uses its own mechanism to show errors on rows and cells, without using an ErrorProvider.)

You can also use the component to get a validation summary for your form using GetError method of the component which return the error message of each control.

ValidateChildren Method and AutoValidate Property of Form

You can use ValidateChildren method of form or your container control to check if there is a validation error for your controls or not.

Based on the value of AutoValidate property of your form, it prevents focus change or let the focus change from invalid controls.

How can I validate only the controls inside a panel?

If you set your Form's AutoValidate mode to EnableAllowFocusChange, and presuming you have validating events hooked up to each of the controls inside your panel, something like this:

private void tb_Validating(object sender, CancelEventArgs e)
{
TextBox tb = sender as TextBox;
if (tb != null)
{
if (tb.Text == String.Empty)
{
errorProvider1.SetError(tb, "Textbox cannot be empty");
e.Cancel = true;
}
else
errorProvider1.SetError(tb, "");
}
}

Then on the Click handler for your save button, you can just do this:

private void SaveButton_Click(object sender, EventArgs e)
{
foreach (Control c in panel1.Controls)
c.Focus();
// If you want to summarise the errors
StringBuilder errorSummary = new StringBuilder();
foreach (Control c in panel1.Controls){
String error = errorProvider1.GetError(c);
if (error != String.Empty)
errorSummary.AppendFormat("{0}{1}", errorProvider1.GetError(c), Environment.NewLine);
}
if(errorSummary.Length>0)
MessageBox.Show(errorSummary.ToString());
}

That will cause the validation to fire on each of the controls within the panel.

C# Validating input for textbox on winforms

Description

There are many ways to validate your TextBox. You can do this on every keystroke, at a later time, or on the Validating event.

The Validating event gets fired if your TextBox looses focus. When the user clicks on a other Control, for example. If your set e.Cancel = true the TextBox doesn't lose the focus.

MSDN - Control.Validating Event When you change the focus by using the keyboard (TAB, SHIFT+TAB, and so on), by calling the Select or SelectNextControl methods, or by setting the ContainerControl.ActiveControl property to the current form, focus events occur in the following order

Enter

GotFocus

Leave

Validating

Validated

LostFocus

When you change the focus by using the mouse or by calling the Focus method, focus events occur in the following order:

Enter

GotFocus

LostFocus

Leave

Validating

Validated

Sample Validating Event

private void textBox1_Validating(object sender, CancelEventArgs e)
{
if (textBox1.Text != "something")
e.Cancel = true;
}

Update

You can use the ErrorProvider to visualize that your TextBox is not valid.
Check out Using Error Provider Control in Windows Forms and C#

More Information

  • MSDN - Control.Validating Event
  • MSDN - ErrorProvider Component (Windows Forms)
  • Using Error Provider Control in Windows Forms and C#

WinForms Validation Without Hanging Other Controls

I found a solution that was so simple, I actually got upset I wasted so many hours of my life banging my head against the keyboard.

Simply set a parent container's ContainerControl.AutoValidate property to EnableAllowFocusChange and problem solved. "Parent container" in this context means the container that actually houses the input controls.

If you have a control hierarchy, you can also set the ContainerControl.AutoValidate property to Inherit and simply set the outermost container to EnableAllowFocusChange.

Hope this helps someone in the future.



Related Topics



Leave a reply



Submit