文本框仅包含数字,但也可以粘贴,复制和选择

时间:2017-07-06 13:01:44

标签: vb.net

我是VB的新手并且坚持(我认为)容易出问题。我有一个只允许数字的文本框:

    Private Sub TextBox2_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox2.KeyPress

    If Asc(e.KeyChar) <> 8 Then
        If Asc(e.KeyChar) < 49 Or Asc(e.KeyChar) > 57 Then
            e.Handled = True
        End If
    End If

End Sub

从1到9.但是这个盒子不允许我粘贴,复制和选择文本......我怎么能改变它?我知道KeyCode for Control是17,而'V'是86,但不知道如何使用它... 谢谢你的帮助

3 个答案:

答案 0 :(得分:1)

KeyPress的问题在于它一次只调用一个KeyPress。因此,Ctrl + V,Ctrl + C等多项选择无效。而不是在KeyPress下标记它,而是调用TextChanged。添加下面提到的问题应该解决。复制,粘贴和选择现在可以正常工作。

Private Sub TextBox2_TextChanged(sender As Object, e As EventArgs) Handles TextBox2.TextChanged
    TextBox2.Text = System.Text.RegularExpressions.Regex.Replace(TextBox2.Text, "[^\d]", "")    'Removes all character except numbers
    TextBox2.Select(TextBox2.Text.Length + 1, 1)    'To bring the textbox focus to the right
End Sub

答案 1 :(得分:0)

如果你一定想要TextBox,你可以合并KeyDownKeyPress个事件,以便在手动允许复制,粘贴,剪切时阻止任何不是数字的事件。等

Imports System.Text.RegularExpressions

Private Sub TextBox2_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox2.KeyPress
    e.Handled = Char.IsNumber(e.KeyChar) = False AndAlso Char.IsControl(e.KeyChar) = False 'Verify if input is a number or a control character (such as Backspace).
End Sub

Private Sub TextBox2_KeyDown(sender As Object, e As KeyEventArgs) Handles TextBox2.KeyDown
    Dim TargetTextBox As TextBox = DirectCast(sender, TextBox)
    e.SuppressKeyPress = True 'Start by blocking all key presses.

    Select Case e.KeyData 'In order to not block some standard keyboard shortcuts.
        Case Keys.Control Or Keys.C 'Copy
            TargetTextBox.Copy()
        Case Keys.Control Or Keys.X 'Cut
            TargetTextBox.Cut()
        Case Keys.Control Or Keys.V 'Paste
            TargetTextBox.Paste()
            TargetTextBox.Text = Regex.Replace(TextBox2.Text, "[^\d]", "")
        Case Keys.Control Or Keys.A 'Select all.
            TargetTextBox.SelectAll()
        Case Else
            e.SuppressKeyPress = False 'Allow all other key presses to be passed on to the KeyPress event.
    End Select
End Sub

编辑:原谅无意识的类似Regex,Arun Kumar。

答案 2 :(得分:0)

这对我有用,请在文本框按键事件上编写以下代码

尝试

        If Asc(e.KeyChar) <> 13 AndAlso Asc(e.KeyChar) <> 8 AndAlso Not IsNumeric(e.KeyChar) AndAlso (e.KeyChar <> Chr(22)) Then
            MsgBox("Please enter numeric values", MsgBoxStyle.Information)
            e.Handled = True
        End If
    Catch ex As Exception
        pObj.WriteErrorLog(Me.GetType().Name, System.Reflection.MethodBase.GetCurrentMethod().Name, ex.Message, ex, True)
    End Try