Back to Devexpress

How to: Prevent Specific Characters From Being Entered Within a Column

windowsforms-3007-controls-and-libraries-data-grid-examples-data-editing-how-to-prevent-specific-characters-from-being-entered-within-a-column.md

latest2.3 KB
Original Source

How to: Prevent Specific Characters From Being Entered Within a Column

  • Nov 13, 2018
  • 2 minutes to read

The following example shows how to prevent numeric characters (‘0’-‘9’) from being entered within a grid’s CustomerID column. Two events are handled to prevent entering these characters:

  • the BaseView.KeyPress event - fires when an alpha numeric character is pressed while an in-place editor is not active;
  • the grid control’s EditorContainer.EditorKeyPress event - fires when an alpha numeric character is pressed while an in-place editor is active.

If a specific character needs to be discarded in these event handlers, the Handled parameter must be set to true.

csharp
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Grid;

// Fires when no in-place editor is active
private void gridView1_KeyPress(object sender, KeyPressEventArgs e) {
    GridView view = sender as GridView;
    string s = "0123456789";
    if (view.FocusedColumn.FieldName == "CustomerID" && s.IndexOf(e.KeyChar) >= 0)
        e.Handled = true;
}
// Fires when an in-place editor is active
private void gridControl1_EditorKeyPress(object sender, KeyPressEventArgs e) {
    GridControl grid = sender as GridControl;
    gridView1_KeyPress(grid.FocusedView, e);
}
vb
Imports System.Windows.Forms
Imports DevExpress.XtraGrid
Imports DevExpress.XtraGrid.Views.Grid

' Fires when no in-place editor is active.
Private Sub GridView1_KeyPress(ByVal sender As System.Object, ByVal e As KeyPressEventArgs) _
  Handles GridView1.KeyPress
    Dim view As GridView = CType(sender, GridView)
    Dim s As String = "0123456789"
    If view.FocusedColumn.FieldName = "CustomerID" And s.IndexOf(e.KeyChar) >= 0 Then
        e.Handled = True
    End If
End Sub

' Fires when an in-place editor is active.
Private Sub GridControl1_EditorKeyPress(ByVal sender As System.Object, _
  ByVal e As KeyPressEventArgs) _
  Handles GridControl1.EditorKeyPress
    Dim grid As GridControl = CType(sender, GridControl)
    GridView1_KeyPress(grid.FocusedView, e)
End Sub