Click here to Skip to main content
15,919,358 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I'm datagridviewtextboxcolumn can only enter numbers from the keyboard. But when I enter through the paste, characters other than numbers can still be entered.Please give me a solution:-0
Thank You
Posted
Updated 14-May-14 5:39am
v2

you may need custom control for that, check below link
Custom Numeric Edit Elements for DataGridView[^]
 
Share this answer
 
You can use the DataGridView's EditingControlShowing event to create and add an event to the textbox. You can add a KeyPress event, KeyUp, KeyDown, TextChanged....anything. You just need a method that has the matching arguments that the textbox event has.

For example, here is what I've used in the past to only allow numeric and decimal points in the textbox of a datagridview:
VB
Private Sub gvMast_EditingControlShowing(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles dgvCLUs.EditingControlShowing

      Select Case e.Control.GetType
           Case GetType(System.Windows.Forms.DataGridViewTextBoxEditingControl)
               Dim txtTemp As TextBox = CType(e.Control, TextBox)

               'Remove the handler before adding it to ensure that the event will only be run once
               'RemoveHandler tmp.PreviewKeyDown, AddressOf MyPreviewKeyDown
               RemoveHandler txtTemp.KeyPress, AddressOf GridTextbox_NumericWithDecimal_KeyPress
               AddHandler txtTemp.KeyPress, AddressOf GridTextbox_NumericWithDecimal_KeyPress

       End Select

   End Sub

    Private Sub GridTextbox_NumericWithDecimal_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs)
        e.Handled = IsNumericWithDecimalKeyPress(e.KeyChar)
    End Sub

    Public Function IsNumericWithDecimalKeyPress(ByVal myKeyChar As Char) As Boolean
        If Char.IsDigit(myKeyChar) Or Char.IsControl(myKeyChar) Or myKeyChar = "." Then
            Return False
        Else
            Return True
        End If
    End Function
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900