DataGridView Numeric Only Cell?

前端 未结 8 639
广开言路
广开言路 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:40

    Try this code

     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
    
            ElseIf DataGridView1.CurrentCell.ColumnIndex = 1 Then
    
                AddHandler CType(e.Control, TextBox).KeyPress, AddressOf TextBox_keyPress1
    
    
            End If
    
        End Sub
    
        Private Sub TextBox_keyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs)
    
            If Char.IsDigit(CChar(CStr(e.KeyChar))) = False Then e.Handled = True
    
        End Sub
    
        Private Sub TextBox_keyPress1(ByVal sender As Object, ByVal e As KeyPressEventArgs)
    
            If Not (Char.IsDigit(CChar(CStr(e.KeyChar))) Or e.KeyChar = ".") Then e.Handled = True
    
        End Sub
    

    TextBox_keyPress Event for only numeric

    TextBox_keyPress1 Event for numeric with decimal value

提交回复
热议问题