如何强制用户从文本框中输入仅包含无整数的字符的字符串? [英] How can I force a user to enter a string with characters only with no integer from a text box?

查看:74
本文介绍了如何强制用户从文本框中输入仅包含无整数的字符的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本框,该文本框仅包含完整的字符串,例如人名.如果用户输入(paul123)或(1234)之类的内容,则应该获得无效的输入.

I have textbox that takes only a fully characters string for example person name. If the user enter something like (paul123) or (1234), it should get an invalid input.

我尝试:

Integer.parse(me.nametextbox.text)
msgbox("invalid")
me.nametextbox.lostfocus

当用户首先键入一个整数时,它起作用了,它给出了消息,但是用户首先键入了它经历的一个字符-那不是我想要的.

It works when the user types an integer first, it gives the message but user types a character first it goes through - that is not what I want.

有什么主意吗?

最好的问候

推荐答案

测试有可能被解释为十六进制数.与其使用TryParse来确定它是否是一个好数字,不如使用正则表达式.

It''s possible that the test is being interpreted as a hexadecimal number. Instead of using TryParse to determine if it''s a good number, use a regular expression instead.


尝试一下 私有Sub me.nametextbox_KeyPress(按对象发送ByVal发送者,按System.Windows.Forms.KeyPressEventArgs接收ByVal e)处理me.nametextbox.KeyPress 如果(不是(Char.IsDigit(e.KeyChar)或Char.IsControl(e.KeyChar))) e.Handled = True:MsgBox(请输入有效的字符.",MsgBoxStyle.Information,消息") 万一 结束Sub
Try This Private Sub me.nametextbox_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles me.nametextbox.KeyPress If (Not (Char.IsDigit(e.KeyChar) Or Char.IsControl(e.KeyChar))) Then e.Handled = True : MsgBox("Please enter valid Char.", MsgBoxStyle.Information, "Message") End If End Sub


"[0-9]"

该正则表达式将在字符串中找到任何数字.因此,您要做的是检查字符串以查看该正则表达式是否返回任何结果.如果是这样,则表示该字符串包含一个数字.我不想让您觉得这太容易(因为我希望您能学习,并且仅在遇到无法解决的问题时才来找我们),所以我将不去理会如何使用正则表达式由您决定.这应该使您入门: .Net正则表达式.

或者,您可以遍历字符串中的每个字符并检查它是否为数字.同样,这应该非常简单,所以我将其留给您练习.

That regular expression will find any digit in a string. So, what you want to do is check the string to see if that regular expression returns any results. If it does, that means the string contains a digit. I don''t want to make it too easy for you (as I expect you to do the learning and only come to us when you are running into a problem you can''t seem to solve), so I will leave figuring out how to use the regular expression up to you. This should get you started: .Net Regular Expressions.

Alternatively, you could just loop through each character in the string and check if it is a digit. Again, that should be extremely simple, so I''ll leave that as an exercise for you to do.


这篇关于如何强制用户从文本框中输入仅包含无整数的字符的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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