我有问题。我需要防止在输入框中输入非数字字符和负数。目前我可以防止非数字字符。如何防止负数。请参阅下面的代码:
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
Dim h1, h2, h3, h4, h5, h6, h7, homeTotal As Integer
Dim v1, v2, v3, v4, v5, v6, v7, visitorsTotal As Integer
Dim prompt, title, prompt1, title1 As String
Dim dataHome As String
Dim dataVisitor As String
If String.IsNullOrEmpty(lblHome1st.Text) And String.IsNullOrEmpty(lblVisitors1st.Text) Then
prompt = "Enter number of home runs: First inning."
title = "Home Runs, first inning."
dataHome = InputBox(prompt, title)
If IsNumeric(dataHome) = False Then
MessageBox.Show("Please enter only numeric values.", "Important Note", MessageBoxButtons.OK)
Else
h1 = Convert.ToInt32(dataHome)
lblHome1st.Text = h1
prompt1 = "Enter number of visitor runs: First inning."
title1 = "Visitors Runs, first inning."
dataVisitor = InputBox(prompt1, title1)
If IsNumeric(dataVisitor) = False Then
MessageBox.Show("Please enter only numeric values.", "Important Note", MessageBoxButtons.OK)
lblHome1st.Text = ""
lblHomeTotal.Text = ""
lblVisitorsTotal.Text = ""
Else
v1 = Convert.ToInt32(dataVisitor)
lblVisitors1st.Text = v1
'Calculate totals
homeTotal = h1
visitorsTotal = v1
'Display totals
lblHomeTotal.Text = homeTotal
lblVisitorsTotal.Text = visitorsTotal
'Display in the list box
listScoreBoard.Items.Add("Innings" & " Home team " & "Visitors")
listScoreBoard.Items.Add("1" & ControlChars.Tab & h1 & ControlChars.Tab & v1)
End If
End If
答案 0 :(得分:0)
E.g。
Dim number As Integer
If Not Integer.TryParse(inputText, number) OrElse number < 0 Then
'Either inputText is not a number or it is a negative number.
End If
或:
Dim number As Integer
If Integer.TryParse(inputText, number) AndAlso number >= 0 Then
'inputText is a non-negative number.
End If
TryParse
类型的Integer
方法不仅会验证,而且如果数据有效,它也会转换。一石二鸟。
答案 1 :(得分:0)
如果您已经在表单上,请考虑使用TextBox
。您可以使用TextBox
,KeyPress
或KeyUp
将输入限制为Keydown
。
在此示例中,您将丢弃以下任何一个按键: - 不是数字,或 - 不是第一个&#34;。&#34; (或者你将使用的任何小数标记)。
虽然这是一个简单的例子 - 我将把编码留作自己的练习。
这只是几行代码 - 用户无法输入任何错误,因此您减少了其他代码中的错误检查。