Datagridview只允许输入数字

第一步:给TextBox注册事件

Private Sub DataGridView1_EditingControlShowing(sender As Object, e As winForms.DataGridViewEditingControlShowingEventArgs) Handles DataGridView1.EditingControlShowing
       If e.Control.GetType Is GetType(winForms.DataGridViewTextBoxEditingControl) Then
            Dim txtEdit As winForms.TextBox = e.Control
            'remove any existing handler
            RemoveHandler txtEdit.KeyPress, AddressOf txtEdit_Keypress
            AddHandler txtEdit.KeyPress, AddressOf txtEdit_Keypress
        End If
    End Sub

第二步:设置允许的按键

复制代码
 Private Sub txtEdit_Keypress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs)

        If DataGridView1.CurrentCell.ColumnIndex = 0 Then

            Dim txtbox As winForms.TextBox = CType(sender, winForms.TextBox)

            '光标位置
            Dim n As Int16 = txtbox.SelectionStart
            '文本框内的字符串’
            Dim t As String = CType(sender, winForms.TextBox).Text

            '----------------------------------------------------------------'
            '如果光标在起始位置并且已经有负号时,什么都不能输入
            '如果光标在起始位置并且没有负号时,允许输入负号’
            '如果没有小数点,允许输入小数点’
            '允许输入数字或退格键’
            '----------------------------------------------------------------'
            If n = 0 AndAlso t.IndexOf("-") > -1 Then
                e.Handled = True
            ElseIf n = 0 AndAlso t.IndexOf("-") < 0 AndAlso e.KeyChar = "-" Then
                e.Handled = False
            ElseIf t.IndexOf(".") < 0 AndAlso e.KeyChar = "." Then
                e.Handled = False
            ElseIf IsNumeric(e.KeyChar.ToString()) OrElse e.KeyChar = ChrW(winForms.Keys.Back) Then
                e.Handled = False
            Else
                e.Handled = True
            End If
        End If
    End Sub
复制代码

 

posted @   rf8862  阅读(466)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示