vb.net - 阻止用户为所有文本框输入字母
问题描述
所以我创建了一个计算器,可以将你的成绩计算为你的总体平均水平。但是我有一个问题,如果用户在每个文本框中输入字母而不是数字怎么办?我想阻止他们使用字母。那么限制用户输入字母的代码是什么?我只需要一个按钮的代码。我将不胜感激!
我已经尝试了网站上的所有代码,但所有代码都不起作用。
If emptyTextBoxes.Any Then
MsgBox("Please fill all the boxes before you press 'Compute'.", MsgBoxStyle.Critical, "GWA Calculator")
ElseIf Math.Text.Count(Function(c) Not Char.IsLetterOrDigit(c)) > 0 Or Eng.Text.Count(Function(c) Not Char.IsLetterOrDigit(c)) > 0 Or
Sci.Text.Count(Function(c) Not Char.IsLetterOrDigit(c)) > 0 Or Fil.Text.Count(Function(c) Not Char.IsLetterOrDigit(c)) > 0 Or
TL.Text.Count(Function(c) Not Char.IsLetterOrDigit(c)) > 0 Or IC.Text.Count(Function(c) Not Char.IsLetterOrDigit(c)) > 0 Or
MAP.Text.Count(Function(c) Not Char.IsLetterOrDigit(c)) > 0 Or Araling.Text.Count(Function(c) Not Char.IsLetterOrDigit(c)) > 0 Or
ES.Text.Count(Function(c) Not Char.IsLetterOrDigit(c)) > 0 Then
MsgBox("One of the boxes has invalid characters", MsgBoxStyle.Critical, "GWA Calculator")
ElseIf (Math.Text.Length <> 2) Or (Eng.Text.Length <> 2) Or (Sci.Text.Length <> 2) Or (Fil.Text.Length <> 2) Or
(TL.Text.Length <> 2) Or (IC.Text.Length <> 2) Or (MAP.Text.Length <> 2) Or (Araling.Text.Length <> 2) Or
(ES.Text.Length <> 2) Then
MsgBox("One of the boxes contains 1 or 3 digits. It must contain 2 digits only to be computed.", MsgBoxStyle.Critical, "GWA Calculator")
在第二个 If 语句中,它只限制这种字符:“/、^、# 等”。我也想限制字母。任何人都可以帮助我吗?
PS 我正在使用 Windows 窗体。
解决方案
假设我有 3 个名为 txtMath、txtEnglish 和 txtScience 的文本框作为数字。当我单击一个按钮时,代码会检查文本框中的所有值是否都可以解析为数字。然后另一个检查所有数字是否在 0 到 99 之间。
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim mathScore, englishScore, scienceScore As Integer
' parse into numbers
Dim scoresAreNumbers =
Integer.TryParse(txtMath.Text, mathScore) AndAlso
Integer.TryParse(txtEnglish.Text, englishScore) AndAlso
Integer.TryParse(txtScience.Text, scienceScore)
' between 0 and 99
Dim scoresAreValid =
(mathScore >= 0 AndAlso mathScore < 100) AndAlso
(englishScore >= 0 AndAlso englishScore < 100) AndAlso
(scienceScore >= 0 AndAlso scienceScore < 100)
If Not scoresAreNumbers Then
MsgBox("One of the values are not numbers")
ElseIf Not scoresAreValid Then
MsgBox("One of the values are not between 0 and 99")
Else
Dim formatScores =
"Math = {0}" & vbNewLine &
"English = {1}" & vbNewLine &
"Science = {2}"
MsgBox(String.Format(formatScores, mathScore, englishScore, scienceScore))
End If
End Sub
推荐阅读
- python - 如何在嵌套外键上使用 Django ORM 进行多个内连接
- testing - Groovy 脚本错误:解析 json 时没有此类属性
- sql - 努力将 Varchar 转换为浮点数
- c# - 对 IN 语句使用具有大量值的 OracleDataReader
- c - 关于无符号和整数表达式的困惑
- c - C 中从 1 到 N 的内存分配
- mysql - Mysql `OR` 条件不适用于 JOIN
- spring - 如何在 Spring 4.1.7 中将模拟注入自定义 ConstraintValidator?
- encryption - RSA 在加密句子时如何工作?
- mysql - 显示订购的所有产品名称列表以及客户的名字和姓氏