Skip to main content

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

  • 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.

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