Category / Section
How to make the grid cell ignore all keys pressed, except numbers in WinForms GridControl?
1 min read
CurrentCellKeyPress event
This can be achieved by handling the CurrentCellKeyPress event of the WinForms GridControl and when the key is not a digit, then set the e.Handled to “True”.
C#
//set the cells of the 3rd column into integer type. this.gridControl1.ColStyles[2].CellValueType = typeof(int); //using CurrentCellKeyPress void gridControl1_CurrentCellKeyPress(object sender, KeyPressEventArgs e) { GridCurrentCell cc = this.gridControl1.CurrentCell; //condition for ignore key other than numbers if (this.gridControl1[cc.RowIndex, cc.ColIndex].CellValueType == typeof(int) && !char.IsDigit(e.KeyChar)) { e.Handled = true; //ignore it MessageBox.Show("Invalid entry"); } }
VB
'set the cells 3rd column into integer type Me.gridControl1.ColStyles[2].CellValueType = GetType(Integer) 'using CurrentCellKeyPress Private Sub gridControl1_CurrentCellKeyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs) Dim cc As GridCurrentCell = Me.gridControl1.CurrentCell 'condition for ignore key other than numbers If Me.gridControl1(cc.RowIndex, cc.ColIndex).CellValueType Is GetType(Integer) AndAlso (Not Char.IsDigit(e.KeyChar)) Then e.Handled = True 'ignore it MessageBox.Show("Invalid entry") End If End Sub
Samples:
C#: IgnoreKeys
VB: IgnoreKeys