验证Visual Basic中的输入

时间:2016-10-02 15:04:41

标签: vb.net

Public Class Form1

'Variables to hold user numeric input 
Private intStay As Integer          'To hold length of stay
Private decMed As Decimal           'To hold med costs
Private decSurgery As Decimal       'To hold surgery costs
Dim decLab As Decimal           'To hold lab costs
Private decRehab As Decimal         'To hold rehab costs

'Variables to hold specific custom messages as strings
Private strStay As String = "Length of Stay"
Private strMed As String = "Medication Costs"
Private strSurgery As String = "Surgery Costs"
Private strLab As String = "Lab Costs"
Private strRehab As String = "Physical Rehab Costs"

'Function that calls on custom string variables and displays
'error message that the cost must be numeric
Private Function NumericMessage(ByVal strFirst As String)
    lblResult.Text = strFirst & " Must Be Numeric"

End Function

'Function that calls on custom string variables and displays
'error message that the cost must be positive
Private Function NegativeMessage(ByRef strFirst As String)
    lblResult.Text = strFirst & " Must Be A Positive Number"

End Function

'Function that tests input from textbox, and if not numeric or positive 
'calls the NumericMessage function or NegativeMessage, respectively
Private Function TestInput(ByVal strInput As String, ByVal decInput As Decimal,
                           ByVal strInputTwo As String) As Boolean
    If Not Decimal.TryParse(strInput, decInput) Then
        NumericMessage(strInputTwo)
        Return False
    ElseIf decInput < 0 Then
        NegativeMessage(strInputTwo)
        Return False
    End If
    Return True
End Function

'Function that calls TestInput and TestPositive functions 
'to test each individual textbox for a positive and numeric number
Private Function ValidateInputFields() As Boolean
    TestInput(txtStay.Text, intStay, strStay)
    TestInput(txtMeds.Text, decMed, strMed)
    TestInput(txtSurgery.Text, decSurgery, strSurgery)
    TestInput(txtLab.Text, decLab, strLab)
    TestInput(txtRehab.Text, decRehab, strRehab)

End Function

Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click

    If ValidateInputFields() Then
        lblResult.Text = decLab.ToString("c")
    End If

End Sub
End Class

因此,当数字不是数字或正数时,我的输入验证工作正常。但是,我似乎无法想到继续进行其他计算的方法。

    If ValidateInputFields() Then
        lblResult.Text = decLab.ToString("c")
    End If

基本上,如果所有输入都经过测试并且没问题,我希望继续使用该程序。 lblResult.Text = decLab.ToString(“c”)将替换为稍后计算的其他函数。谢谢。

0 个答案:

没有答案