VB.net 需要文本框只接受数字 [英] VB.net Need Text Box to Only Accept Numbers

查看:47
本文介绍了VB.net 需要文本框只接受数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 TextBox that 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.

 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()

推荐答案

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

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

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

这篇关于VB.net 需要文本框只接受数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆