1) Set KeyPreview property on the form to true
2) Create a private Boolean Variable Called ColumnProtectionOn which is visible to the whole form and all its associated controls
3) In the CellEnter event of the DataGridView test for the column that you want to protect using If e.ColumnIndex = 2 etc and set the ColumnProtectionOn=True
3) In the CellLeave event of the DataGridView set the ColumnProtectionOn =False
4) In the form KeyDown event enter the following code:-
VB.NET:
If ColumnProtectionOn Then
If Not e.KeyCode = Keys.Tab And Not e.KeyCode = Keys.Enter Then
If Not IsNumeric(Convert.ToChar(e.KeyValue)) Then
e.SuppressKeyPress = True
End If
End If
End If
That's It. What happens is the when you enter the column to protect it sets the ColumnProtectionOn variable to true so that when you press keys on the keyboard it tests every key press to see what was typed. If a letter was typed then it suppresses the keystroke so that only numbers can be entered. It also tests for the tab and enter key to ensure is does not stop you from leaving the cell after entry.
Hope this helps.
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.