DataGridView Numeric Only Cell?

前端 未结 8 656
广开言路
广开言路 2021-01-06 07:33

I am new to winforms..I am trying to set two column of DataGridView to Numeric Only.. I do not want user to be able to type anything into a cell unless its a natural number

8条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-06 07:47

    Try this code. Its almost the same as the most votes answer, but I edited KeypressEvent codes to make it simple and you can use this even you have to enter decimal numbers. Enjoy. :)

    Private Sub DataGridView1_EditingControlShowing(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles DataGridView1.EditingControlShowing
    
        If DataGridView1.CurrentCell.ColumnIndex = 2 Then
    
            AddHandler CType(e.Control, TextBox).KeyPress, AddressOf TextBox_keyPress
    
        End If
    
    End Sub
    
    Private Sub TextBox_keyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs)
    
         If (Not Char.IsControl(e.KeyChar) _
                    AndAlso (Not Char.IsDigit(e.KeyChar) _
                    AndAlso (e.KeyChar <> Microsoft.VisualBasic.ChrW(46)))) Then
            e.Handled = True
        End If
    
    End Sub
    

提交回复
热议问题