Back to Devexpress

How to: Validate Data Entered by End-Users

windowsforms-3055-controls-and-libraries-data-grid-examples-data-editing-how-to-validate-data-entered-by-end-users.md

latest3.0 KB
Original Source

How to: Validate Data Entered by End-Users

  • Nov 13, 2018
  • 2 minutes to read

The following example prohibits invalid “colBudget” column cell value assignment. The cell value should be grater than zero and less than 1,000,000. The BaseView.ValidatingEditor event is handled to check the entered value’s validity. The BaseView.InvalidValueException event is handled to display an exception message box if invalid cell value assignment occurs. In this instance, the GridView.HideEditor method is called to discard the changes made and to destroy the cell’s editor.

csharp
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraGrid.Views.Base;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Columns;

private void gridView1_ValidatingEditor(object sender, BaseContainerValidateEditorEventArgs e) {
    ColumnView view = sender as ColumnView;
    GridColumn column = (e as EditFormValidateEditorEventArgs)?.Column ?? view.FocusedColumn;
    if (column.Name != "colBudget") return;
    if ((Convert.ToInt32(e.Value) < 0) || (Convert.ToInt32(e.Value) > 1000000))
        e.Valid = false;
}

private void gridView1_InvalidValueException(object sender, InvalidValueExceptionEventArgs e) {
    ColumnView view = sender as ColumnView;
    if (view == null) return;
    e.ExceptionMode = ExceptionMode.DisplayError;
    e.WindowCaption = "Input Error";
    e.ErrorText = "The value should be greater than 0 and less than 1,000,000";
    // Destroy the editor and discard the changes made within the edited cell.
    view.HideEditor();
}
vb
Imports DevExpress.XtraEditors.Controls
Imports DevExpress.XtraGrid.Views.Base
Imports DevExpress.XtraGrid.Views.Grid
Imports DevExpress.XtraGrid.Columns

Private Sub GridView1_ValidatingEditor(sender As Object, e As DevExpress.XtraEditors.Controls.BaseContainerValidateEditorEventArgs) Handles GridView1.ValidatingEditor
    Dim view As ColumnView = sender
    Dim column As GridColumn = If(TryCast(e, EditFormValidateEditorEventArgs)?.Column, view.FocusedColumn)
    If column.Name <> "colBudget" Then Exit Sub
    If (Convert.ToInt32(e.Value) < 0) Or (Convert.ToInt32(e.Value) > 1000000) Then
        e.Valid = False
    End If
End Sub

Private Sub GridView1_InvalidValueException(sender As Object, e As DevExpress.XtraEditors.Controls.InvalidValueExceptionEventArgs) Handles GridView1.InvalidValueException
    Dim view As ColumnView = sender
    If view Is Nothing Then
        Return
    End If
    e.ExceptionMode = ExceptionMode.DisplayError
    e.WindowCaption = "Input Error"
    e.ErrorText = "The value should be greater than 0 and less than 1,000,000"
    ' Destroy the editor and discard the changes made within the edited cell
    view.HideEditor()
End Sub