VB.net 需要文本框只接受数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9969824/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 16:01:57  来源:igfitidea点击:

VB.net Need Text Box to Only Accept Numbers

vb.nettextboxnumbers

提问by Rico Hymanson

I'm fairly new to VB.net (self taught) and was just wondering if someone out there could help me out with some code. I'm not trying to do anything too involved, just have a TextBoxthat accepts a numeric value from 1 to 10. I don't want it to accept a string or any number above 10. If someone types a word or character an error message will appear, telling him to enter a valid number. This is what I have; obviously it's not great as I am having problems. Thanks again to anyone who can help.

我对 VB.net(自学)相当陌生,只是想知道是否有人可以帮助我解决一些代码。我不想做任何太复杂的事情,只是有一个TextBox接受从 1 到 10 的数值。我不希望它接受一个字符串或任何大于 10 的数字。如果有人键入一个单词或字符,则会出现错误消息会出现,告诉他输入一个有效的数字。这就是我所拥有的;显然这不是很好,因为我遇到了问题。再次感谢任何可以提供帮助的人。

 If TxtBox.Text > 10 Then
        MessageBox.Show("Please Enter a Number from 1 to 10")
        TxtBox.Focus()
    ElseIf TxtBox.Text < 10 Then
        MessageBox.Show("Thank You, your rating was " & TxtBox.Text)
        Total = Total + 1
    ElseIf IsNumeric(TxtBox.Text) Then
        MessageBox.Show("Thank you, your rating was " & ValueTxtBox.Text)
    End If

    ValueTxtBox.Clear()
    ValueTxtBox.Focus()

回答by Isuru

You can do this with the use of Ascii integers. Put this code in the Textbox's Keypress event. e.KeyCharrepresents the key that's pressed. And the the built-in function Asc()converts it into its Ascii integer.

您可以使用 Ascii 整数来做到这一点。将此代码放在文本框的 Keypress 事件中。e.KeyChar代表按下的键。内置函数Asc()将其转换为 Ascii 整数。

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

    '97 - 122 = Ascii codes for simple letters
    '65 - 90  = Ascii codes for capital letters
    '48 - 57  = Ascii codes for numbers

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

End Sub

回答by BCarpe

This is what I did in order to handle both key entry and copy/paste.

这就是我为了处理密钥输入和复制/粘贴所做的工作。

Private Sub TextBox_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox.KeyPress
    If Not Char.IsNumber(e.KeyChar) AndAlso Not Char.IsControl(e.KeyChar) Then
        e.Handled = True
    End If
End Sub

Private Sub TextBox_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox.TextChanged
    Dim digitsOnly As Regex = New Regex("[^\d]")
    TextBox.Text = digitsOnly.Replace(TextBox.Text, "")
End Sub

If you want to allow decimals, add

如果要允许小数,请添加

AndAlso Not e.KeyChar = "."

to the if statement in the KeyPress section.

到 KeyPress 部分中的 if 语句。

回答by Avadhani

Try this:

尝试这个:

Private Sub txtCaseID_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtCaseID.KeyPress
    If Not Char.IsNumber(e.KeyChar) AndAlso Not Char.IsControl(e.KeyChar) Then e.KeyChar = ""
End Sub

回答by Meta-Knight

You must first validate if the input is actually an integer. You can do it with Integer.TryParse:

您必须首先验证输入是否实际上是一个整数。你可以这样做Integer.TryParse

Dim intValue As Integer
If Integer.TryParse(TxtBox.Text, intValue) AndAlso intValue > 0 AndAlso intValue < 11 Then
    MessageBox.Show("Thank You, your rating was " & TxtBox.Text)
Else
    MessageBox.Show("Please Enter a Number from 1 to 10")
End If

回答by bendataclear

You could avoid any code by using a NumericUpDown control rather than a text box, this automatically only allows numbers and has a max and min. It also allow accessing the number directly with NumericUpDown1.Valueas well as using up and down arrows to set the number. Also if a number higher/over the max is entered it will jump to the nearest allowed number.

您可以通过使用 NumericUpDown 控件而不是文本框来避免任何代码,这会自动只允许数字并具有最大值和最小值。它还允许直接访问号码NumericUpDown1.Value以及使用向上和向下箭头来设置号码。此外,如果输入的数字高于/超过最大值,它将跳转到最近的允许数字。

回答by Roy

Private Sub MyTextBox_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles MyTextBox.KeyPress
    If Not IsNumeric(e.KeyChar) And Not e.KeyChar = ChrW(Keys.Back) Then
        e.Handled = True
    End If
End Sub

回答by Laxmikant Bhumkar

Simplest ever solution for TextBox Validation in VB.NET

VB.NET 中最简单的文本框验证解决方案

TextBox Validation for Visual Basic (VB.NET)

Visual Basic (VB.NET) 的文本框验证

First, add new VB code file in your project.

首先,在您的项目中添加新的 VB 代码文件。

  1. Go To Solution Explorer
  2. Right Clickto your project
  3. Select Add> New item...
  4. Add new VB code file (i.e. example.vb)
  1. 转到解决方案资源管理器
  2. 右键单击您的项目
  3. 选择添加>新建项目...
  4. 添加新的VB代码文件(即example.vb)

orpress Ctrl+Shift+A

Ctrl+ Shift+A

COPY & PASTE following code into this file and give it a suitable name. (i.e. KeyValidation.vb)

将以下代码复制并粘贴到此文件中并为其指定合适的名称。(即 KeyValidation.vb)

Imports System.Text.RegularExpressions
Module Module1
    Public Enum ValidationType
        Only_Numbers = 1
        Only_Characters = 2
        Not_Null = 3
        Only_Email = 4
        Phone_Number = 5
    End Enum
    Public Sub AssignValidation(ByRef CTRL As Windows.Forms.TextBox, ByVal Validation_Type As ValidationType)
        Dim txt As Windows.Forms.TextBox = CTRL
        Select Case Validation_Type
            Case ValidationType.Only_Numbers
                AddHandler txt.KeyPress, AddressOf number_Leave
            Case ValidationType.Only_Characters
                AddHandler txt.KeyPress, AddressOf OCHAR_Leave
            Case ValidationType.Not_Null
                AddHandler txt.Leave, AddressOf NotNull_Leave
            Case ValidationType.Only_Email
                AddHandler txt.Leave, AddressOf Email_Leave
            Case ValidationType.Phone_Number
                AddHandler txt.KeyPress, AddressOf Phonenumber_Leave
        End Select
    End Sub
    Public Sub number_Leave(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs)
        Dim numbers As Windows.Forms.TextBox = sender
        If InStr("1234567890.", e.KeyChar) = 0 And Asc(e.KeyChar) <> 8 Or (e.KeyChar = "." And InStr(numbers.Text, ".") > 0) Then
            e.KeyChar = Chr(0)
            e.Handled = True
        End If
    End Sub
    Public Sub Phonenumber_Leave(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs)
        Dim numbers As Windows.Forms.TextBox = sender
        If InStr("1234567890.()-+ ", e.KeyChar) = 0 And Asc(e.KeyChar) <> 8 Or (e.KeyChar = "." And InStr(numbers.Text, ".") > 0) Then
            e.KeyChar = Chr(0)
            e.Handled = True
        End If
    End Sub
    Public Sub OCHAR_Leave(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs)
        If InStr("1234567890!@#$%^&*()_+=-", e.KeyChar) > 0 Then
            e.KeyChar = Chr(0)
            e.Handled = True
        End If
    End Sub
    Public Sub NotNull_Leave(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim No As Windows.Forms.TextBox = sender
        If No.Text.Trim = "" Then
            MsgBox("This field Must be filled!")
            No.Focus()
        End If
    End Sub
    Public Sub Email_Leave(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim Email As Windows.Forms.TextBox = sender
        If Email.Text <> "" Then
            Dim rex As Match = Regex.Match(Trim(Email.Text), "^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,3})$", RegexOptions.IgnoreCase)
            If rex.Success = False Then
                MessageBox.Show("Please Enter a valid Email Address", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information)
                Email.BackColor = Color.Red
                Email.Focus()
                Exit Sub
            Else
                Email.BackColor = Color.White
            End If
        End If
    End Sub
End Module

Now use following code to Form Load Event like below.

现在使用以下代码来形成如下所示的加载事件。

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        AssignValidation(Me.TextBox1, ValidationType.Only_Digits)
        AssignValidation(Me.TextBox2, ValidationType.Only_Characters)
        AssignValidation(Me.TextBox3, ValidationType.No_Blank)
        AssignValidation(Me.TextBox4, ValidationType.Only_Email)
End Sub

Done..!

完毕..!

回答by Er Harry Singh

Private Sub textBox5_KeyPress(sender As System.Object, e As System.Windows.Forms.KeyPressEventArgs) Handles textBox5.KeyPress
        If Asc(e.KeyChar) <> 8 Then
            If Asc(e.KeyChar) < 48 Or Asc(e.KeyChar) > 57 Then
                e.Handled = True
            End If
        End If
    End Sub

回答by moustafaghaddar

Private Sub Data_KeyPress(sender As Object, e As KeyPressEventArgs) Handles Data.KeyPress
    If (Not e.KeyChar = ChrW(Keys.Back) And ("0123456789.").IndexOf(e.KeyChar) = -1) Or (e.KeyChar = "." And Data.Text.ToCharArray().Count(Function(c) c = ".") > 0) Then
        e.Handled = True
    End If
End Sub

回答by Mr_LinDowsMac

If Not Char.IsNumber(e.KeyChar) AndAlso Not e.KeyChar = "." AndAlso Not Char.IsControl(e.KeyChar) Then
            e.KeyChar = ""
End If

This allow you to use delete key and set decimal points

这允许您使用删除键并设置小数点