不确定如何在显示所有验证响应时执行连续验证



我试图在4个不同的用户输入分数上完成相同的验证(存在,数值,范围检查),并在不同的行上的单个标签中显示所有测试的结果。有人能帮忙吗?

这是当前的代码,但只有1分检查,我不知道如何改变它,因为我是相当新的vb.net

Private Sub ValidateData()
        'Declares the class level variables for this procedure
        lblStatusDisplay.Text = ""
        S1 = Val(txtScore1.Text)
        S2 = Val(txtScore2.Text)
        S3 = Val(txtScore3.Text)
        S4 = Val(txtScore4.Text)
        Total = S1 + S2 + S3 + S4

        lblStatusDisplay.Text = ""
        S = Val(txtScore1.Text)
        If S = "" Then
            lblStatusDisplay.Text = vbCrLf & "No data has been entered for Score 1"
        ElseIf Not IsNumeric(txtScore1.Text) Then
            lblStatusDisplay.Text = vbCrLf & "Please enter a numerical value for Score 1"
        ElseIf Val(S) < 0 Or Val(S) > 10 Then
            lblStatusDisplay.Text = vbCrLf & "Please enter a number between 0 and 10 for Score 1"
        Else
            lblStatusDisplay.Text = vbCrLf & "Score 1 is valid"
            S = Val(txtScore2.Text)
            If S = "" Then
                lblStatusDisplay.Text = vbCrLf & "No data has been entered for Score 1"
            ElseIf Not IsNumeric(txtScore1.Text) Then
                lblStatusDisplay.Text = vbCrLf & "Please enter a numerical value for Score 1"
            ElseIf Val(S) < 0 Or Val(S) > 10 Then
                lblStatusDisplay.Text = vbCrLf & "Please enter a number between 0 and 10 for Score 1"
            Else
                lblStatusDisplay.Text = vbCrLf & "Score 1 is valid"
                S = Val(txtScore2.Text)
            End If
        End If
    End Sub

获取文本框的集合,然后遍历它,可以节省代码中的大量重复。看看是否有帮助:

Private Sub ValidateData()
    lblStatusDisplay.Text = ""
    Total = 0
    'This iterates through all the textboxes whose names start with "txtScore"
    For Each tb In Me.Controls.OfType(Of TextBox).Where(Function(x) x.Name.StartsWith("txtScore"))
        Dim tempnum = 0
        If tb.Text = "" Then
            lblStatusDisplay.Text += vbCrLf & "No data has been entered for Score " & tb.Name.Last
        'Using tryparse here checks if the text is a number and initializes the 
        'temp variable for the next elseif
        ElseIf Not Integer.TryParse(tb.Text, tempnum) Then
            lblStatusDisplay.Text += vbCrLf & "Please enter a numerical value for Score " & tb.Name.Last
        ElseIf tempnum < 0 Or tempnum > 10 Then
            lblStatusDisplay.Text += vbCrLf & "Please enter a number between 0 and 10 for Score " & tb.Name.Last
        Else
            lblStatusDisplay.Text += vbCrLf & "Score " & tb.Name.Last & " is valid"
            Total += tempnum
        End If
    Next
    lblSatusDisplay.Text = lblStatusDisplay.Text.Trim(vbCrLf.ToCharArray)
End Sub

如果不使用Double,则假定分数都是整数。TryParse

相关内容

  • 没有找到相关文章

最新更新