我目前正试图在我的if / else语句中找到错误我运行了一些小测试,看看我的变量是否保持值,但是当我点击提交按钮时,我一直变为零。
Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles Pack_Weight.TextChanged
End Sub
Protected Sub Submit_Button_Click(sender As Object, e As EventArgs) Handles Submit_Button.Click
Dim PackageW, MemphisRate, SanFranRate As Double
'takes user input from the textbox and places it in the variable
PackageW = Pack_Weight.Text
'if user selects the dropbox and radiobutton list the selected combo should charge a varying bag fee
If Location.SelectedValue = "1" & ShippingList.SelectedValue = "1" Then
MemphisRate = 2.2 * PackageW
ElseIf Location.SelectedValue = "1" & ShippingList.SelectedValue = "2" Then
MemphisRate = 2.59 * PackageW
ElseIf Location.SelectedValue = "1" & ShippingList.SelectedValue = "3" Then
MemphisRate = 2.92 * PackageW
End If
'outputs the user selected combo to the total amount textbox
Total_Cost.Text = MemphisRate
If Location.SelectedValue = "2" & ShippingList.SelectedValue = "1" Then
SanFranRate = 2.2 * PackageW
ElseIf Location.SelectedValue = "2" & ShippingList.SelectedValue = "2" Then
SanFranRate = 2.59 * PackageW
ElseIf Location.SelectedValue = "2" & ShippingList.SelectedValue = "3" Then
SanFranRate = 2.92 * PackageW
End If
Total_Cost.Text = SanFranRate
End Sub
End Class
答案 0 :(得分:0)
您错误地使用了&
。在VB.NET中,&
运算符用于字符串连接。您应该使用关键字And
或AndAlso
代替。
答案 1 :(得分:0)
在尝试处理输入之前,您应该执行输入验证。
使用Option Strict On可确保所有数据类型都匹配,例如它会阻止你尝试将字符串分配给数字变量。
当您计算货币值时,最好使用Decimal类型而不是Double。
其中有很多If... ElseIf
- 使用Select Case
看起来有点整洁,如下所示:
Option Strict On
' ...
Protected Sub Submit_Button_Click(sender As Object, e As EventArgs) Handles Submit_Button.Click
Dim packageW As Decimal
' INPUT VALIDATION
If Not Decimal.TryParse(Pack_Weight.Text, packageW) Then
' inform user that a number is required
Exit Sub
End If
If Location.SelectedIndex = -1 Then
' inform user that a location must be selected
Exit Sub
End If
If ShippingList.SelectedIndex = -1 Then
' inform user that a shipping type must be selected
Exit Sub
End If
' CALCULATE SHIPPING COST
Dim shippingRate As Decimal = 0D
Select Case Location.SelectedItem.Text
Case "1" ' Memphis
Select Case ShippingList.SelectedItem.Text
Case "1" ' Economy
shippingRate = 2.2D
Case "2" ' Normal
shippingRate = 2.59D
Case "3" ' Speedy
shippingRate = 2.92D
End Select
Case "2" ' San Francisco
Select Case ShippingList.SelectedItem.Text
Case "1"
shippingRate = 2.2D
Case "2"
shippingRate = 2.59D
Case "3"
shippingRate = 2.92D
End Select
End Select
Dim shippingCost As Decimal = Math.Round(packageW * shippingRate, 2)
Total_Cost.Text = shippingRate.ToString()
End Sub
我发现.SelectedItem.Text
比.SelectedValue
更可靠。
我不清楚某些变量的名称是什么 - 你应该改变它们才有意义。
从代码中的注释中可以看出,如果没有选择的状态是有效的 - 如果是,请取出.SelectedIndex = 1
的检查。您可能希望确保用户输入了有效的packageW
,即不是负数且不是非常大。