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

编程入门 行业动态 更新时间:2024-10-24 04:38:30
本文介绍了VB 需要文本框只接受数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

I'm fairly new to VB (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 需要文本框只接受数字

本文发布于:2023-11-03 20:33:51,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1556020.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文本框   数字   VB   net

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!