我刚开始上VB的第一堂课,我的老师在48小时内没有回复电子邮件,我的项目即将到期。我希望你们能帮助我解决这个问题。我想要做的是获得一个程序来计算3个文本框的总数,并将其显示在一个标签中。问题是,3个文本框中的输入不能是负数。我试图设置它,所以当输入负数时,它会显示一条消息,只输入正数。但是,每次运行程序时,它只计算带有负数的文本框为0,并完成剩余的计算。这是我的代码:
Private Sub btnCalc_Click(sender As Object, e As EventArgs) Handles btnCalc.Click
Dim intPackA As Integer
Dim intPackB As Integer
Dim intPackC As Integer
Dim intCalc As Integer
Try
If txtPackA.Text Or txtPackB.Text Or txtPackC.Text <= 0 Then
lblCalc.Text = "Please enter positive numeric values"
End If
If txtPackA.Text >= 0 Then
intPackA = txtPackA.Text * 79.2
Else
lblCalc.Text = "Please enter positive numeric values"
End If
If txtPackB.Text >= 0 Then
intPackB = txtPackB.Text * 119.4
Else
lblCalc.Text = "Please enter positive numeric values"
End If
If intPackC >= 0 Then
intPackC = txtPackC.Text * 149.5
Else
lblCalc.Text = "Please enter positive numeric values"
End If
intCalc = intPackA + intPackB + intPackC
lblCalc.Text = "Package A: " & intPackA.ToString("c") + vbCrLf & "Package B: " & intPackB.ToString("c") + vbCrLf & "Package C: " & intPackC.ToString("c") + vbCrLf + vbCrLf & "Grand Total: " & intCalc.ToString("c")
Catch
lblCalc.Text = "Please enter positive numeric values"
End Try
End Sub
我知道其他一些if语句是多余的,但是如果你能给我一些简单的方法来浓缩和清理,我会很感激。
答案 0 :(得分:2)
首先使用TryParse
将您的String输入从Textbox转换为Integer(并将其存储到Integer变量),然后进行比较:
Dim valueA, valueB, valueC As Integer
Dim intPackA, intPackB, intPackC, intCalc As Integer
Int32.TryParse(txtPackA.Text, valueA)
Int32.TryParse(txtPackB.Text, valueB)
Int32.TryParse(txtPackC.Text, valueC)
If valueA <=0 Or valueB <= 0 Or valueC <= 0 Then
lblCalc.Text = "Please enter positive numeric values"
Exit Sub
End If
做其余的服务,否则你就没有更多的学习经验了。
答案 1 :(得分:0)
而不是
If txtPackA.Text Or txtPackB.Text Or txtPackC.Text <= 0 Then
lblCalc.Text = "Please enter positive numeric values"
End If
使用此
If txtPackA.Text <= 0 Then
lblCalc.Text = "Please enter positive numeric values"
txtPackA.Focus()
Exit Sub
ElseIf txtPackB.Text <= 0 Then
lblCalc.Text = "Please enter positive numeric values"
txtPackB.Focus()
Exit Sub
ElseIf txtPackC.Text <= 0 Then
lblCalc.Text = "Please enter positive numeric values"
txtPackC.Focus()
Exit Sub
End If
答案 2 :(得分:0)
你需要这个........
Private Sub TB_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtPackA.KeyPress, txtPackB.KeyPress, txtPackC.KeyPress
Dim sN As String = "0123456789"
Dim sO As String = Chr(8) & Chr(13) & Chr(1) & Chr(3) & Chr(22)
If Not (sN & sO).Contains(e.KeyChar) Then
e.Handled = True
End If
End Sub
Private Sub TB_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtPackA.TextChanged, txtPackB.TextChanged, txtPackC.TextChanged
lblCalc.Text = format(val(txtPackA.Text) + val(txtPackB.Text) + val(txtPackC.Text))
End Sub