Skip to main content

Tutorial: Data Input Validation

  • 5 minutes to read

Tutorial Video

Default Data Validation

The grid control has built-in data type validation enabled by default. If you enter a string value into a column bound to a numeric data field, and then, press ENTER or try to move focus away from the cell, the grid validates data input and raises an error as the string cannot be converted to a numeric value. Hover over the error icon to see the same error message.

GridView_BuiltInDataValidation

Correct the entered value or discard changes to continue working with the grid control. To cancel your changes, press ESCAPE.

Change the Default Error Message

To manually specify the default error message, do the following.

  1. Handle the View’s BaseView.ValidatingEditor event.
  2. In the event handler, check the focused column using the GridColumn.FieldName property.
  3. Try converting the event’s BaseContainerValidateEditorEventArgs.Value parameter to a required type.
  4. If the value cannot be converted, set the BaseContainerValidateEditorEventArgs.Valid parameter to false and specify your custom BaseContainerValidateEditorEventArgs.ErrorText property value.
private void gridView1_ValidatingEditor(object sender, BaseContainerValidateEditorEventArgs e) {
    GridView view = sender as GridView;
    if (view.FocusedColumn.FieldName == "UnitPrice") {
        double price = 0;
        if (!Double.TryParse(e.Value as String, out price)) {
            e.Valid = false;
            e.ErrorText = "Only numeric values are accepted.";
        }
    }
}

Run the application to see how the validation mechanism now shows your custom-defined error message.

GridView_CustomErrorMessage

Provide a Custom Data Validation Rule

To validate data, do the following:

  1. Handle the same BaseView.ValidatingEditor event.
  2. To allow only positive numeric values in a specific column, check that the converted value is greater than 0.
  3. If it is not, set the BaseContainerValidateEditorEventArgs.Valid parameter to false and specify your custom error message.
private void gridView1_ValidatingEditor(object sender, BaseContainerValidateEditorEventArgs e) {
    GridView view = sender as GridView;
    if (view.FocusedColumn.FieldName == "UnitPrice") {
        double price = 0;
        if (!Double.TryParse(e.Value as String, out price)) {
            e.Valid = false;
            e.ErrorText = "Only numeric values are accepted.";
        }
        else if (price <= 0) {
            e.Valid = false;
            e.ErrorText = "The unit price must be positive.";
        }
    }
}

If you run the application, you will see that the specified error message appears on an attempt to enter zero into a cell.

GridView_CustomValidationRule

Display the Exception Message Box

To customize how errors are displayed, do the following.

  1. Handle the View’s BaseView.InvalidValueException event.
  2. In the event handler, show the message box with the ExceptionEventArgs.ErrorText property value.
  3. To suppress the default error icon and tooltip, set the ExceptionEventArgs.ExceptionMode parameter to ExceptionMode.NoAction.
private void gridView1_InvalidValueException(object sender, InvalidValueExceptionEventArgs e) {
    MessageBox.Show(this, e.ErrorText, "Invalid Value", MessageBoxButtons.OK, MessageBoxIcon.Error);
    e.ExceptionMode = ExceptionMode.NoAction;
}

The grid control now informs you about the error using the Message Box.

GridView_ExceptionMessageBox

Enable Row Validation

If a value’s validity depends on other values within the same row, you can enable row validation by handling the ColumnView.ValidateRow event.

For instance, make sure that values in one column are greater than values in another column.

  1. In the ValidateRow event handler, obtain the required column objects.
  2. Use the View’s ColumnView.GetRowCellValue method to determine column values in the focused row.
  3. Check if one value is greater than the other.
  4. Set error messages to column cells using the ColumnView.SetColumnError method. Use a column object as the first parameter and error message string as the second parameter.
  5. To assign an error to the entire row, call the ColumnView.SetColumnError method with the first parameter set to null.
  6. Set the event’s ValidateRowEventArgs.Valid parameter to false and ValidateRowEventArgs.ErrorText to your custom error message.
private void gridView1_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e) {
    GridView view = sender as GridView;
    GridColumn colUnitsInStock = view.Columns["UnitsInStock"];
    GridColumn colUnitsOnOrder = view.Columns["UnitsOnOrder"];

    double unitsInStock = Convert.ToDouble(view.GetRowCellValue(view.FocusedRowHandle, colUnitsInStock));
    double unitsOnOrder = Convert.ToDouble(view.GetRowCellValue(view.FocusedRowHandle, colUnitsOnOrder));
    if (unitsInStock < unitsOnOrder) {
        view.SetColumnError(colUnitsInStock, "The Units On Order value should be less than this value.");
        view.SetColumnError(colUnitsOnOrder, "This value should be less than the Units In Stock value.");
        view.SetColumnError(null, "Invalid data");
        e.Valid = false;
        e.ErrorText = "'Units On Order' and 'Units In Stock' values are not consistent.";
    }
}

Run the application, enter the invalid value and try to switch focus to another row. This is when row validation takes place and the default Error Dialog with the specified error text is invoked.

GridView_DefaultErrorDialog

Click Yes and then hover over error icons to see error messages specified for individual columns.

GridView_RowValidationResult

Suppress the Default Error Message Box

To disable the default dialog window when validating rows, handle the ColumnView.InvalidRowException event and set the ExceptionEventArgs.ExceptionMode parameter to ExceptionMode.NoAction

private void gridView1_InvalidRowException(object sender, DevExpress.XtraGrid.Views.Base.InvalidRowExceptionEventArgs e) {
    e.ExceptionMode = ExceptionMode.NoAction;
}

The message is now suppressed when entering incorrect values, but you can still see the same error icons in data cells and the row indicator area.

See Also