我在vb.net中进行编程时,我是一个完整的新手(上周开始)。我在课堂上有一个分配,要求我使用3个复选框进行运行总计。
我已经找到了一点。我现在的主要问题是,当我取消选中框时,计算会变得很奇怪。到目前为止,这是我的代码:
Public Class frm1
Dim HandbagAcc As Double = 0
Private Sub chkBoxExtra_CheckedChanged(sender As Object, e As EventArgs) Handles chkBoxExtra.CheckedChanged
'$9.99
If chkBoxExtra.Checked = True Then
HandbagAcc = HandbagAcc + 9.99
txtBoxAcc.Text = FormatCurrency(HandbagAcc)
End If
If chkBoxExtra.Checked = False Then
HandbagAcc = HandbagAcc - 9.99
txtBoxAcc.Text = FormatCurrency(HandbagAcc)
End If
End Sub
Private Sub chkBoxMatching_CheckedChanged(sender As Object, e As EventArgs) Handles chkBoxMatching.CheckedChanged
'$7.99
If chkBoxExtra.Checked = True Then
HandbagAcc = HandbagAcc + 7.99
txtBoxAcc.Text = FormatCurrency(HandbagAcc)
End If
If chkBoxExtra.Checked = False Then
HandbagAcc = HandbagAcc - 7.99
txtBoxAcc.Text = FormatCurrency(HandbagAcc)
End If
End Sub
Private Sub chkBoxFour_CheckedChanged(sender As Object, e As EventArgs) Handles chkBoxFour.CheckedChanged
'$3.95
If chkBoxExtra.Checked = True Then
HandbagAcc = HandbagAcc + 3.95
txtBoxAcc.Text = FormatCurrency(HandbagAcc)
End If
If chkBoxExtra.Checked = False Then
HandbagAcc = (HandbagAcc - 3.95)
txtBoxAcc.Text = FormatCurrency(HandbagAcc)
End If
End Sub
End Class
首次检查三个复选框时,值又加起来了 - 但是当我取消选中一两个盒子时,我的数字会发出常声,计算不会加起来。我究竟做错了什么?
任何帮助将不胜感激。谢谢!
,因此您在两个处理程序中检查了错误的复选框。
无论如何,我想对代码提供一些改进。如果将价格添加到复选框中作为标签,则可以大大减少所需的代码数量。
Dim HandbagAcc As Double = 0
Private Sub AnyCheckBox_CheckChanged(sender As Object, e As EventArgs) Handles chkBoxExtra.CheckedChanged, chkBoxMatching.CheckedChanged, chkBoxFour.CheckedChanged
Dim currentChk As CheckBox = sender
Dim price As Double = currentChk.Tag
HandbagAcc = HandbagAcc + If(currentChk.Checked, price, -price)
txtBoxAcc.Text = FormatCurrency(HandbagAcc)
End Sub
因此,添加了标签后,您不需要每个处理程序,并且可以通过同一处理程序运行。 Handles chkBoxExtra.CheckedChanged, chkBoxMatching.CheckedChanged, chkBoxFour.CheckedChanged
通过sender
参数抓住特定的复选框并将其施放到CheckBox
,因此您可以访问该类型的特定属性。
抓住标签并将其投入到 Double
,因此您可以从总计中添加/减去。
现在这条线:
HandbagAcc = HandbagAcc + If(currentChk.Checked, price, -price)
内联If
允许您紧凑以下内容:
If currentChk.Checked Then
HandbagAcc += price
Else
HandbagAcc -= price
End If
+=
是做x = x + y
更简单的方法,使用更灵活的属性
删除
Dim HandbagAcc As Double = 0
替换
Public ReadOnly Property HandbagAcc() as Double
Get
Dim Sum As Double
If chkBoxExtra.Checked Then Sum += 9.99
If chkBoxMatching.checked Then Sum += 7.99
If chkBoxFour.Checked Then Sum += 3.95
Return Sum
End Get
End Sub
创建普通处理程序
Private Sub AnyCheckBox_CheckChanged(sender As Object, e As EventArgs) _
Handles _
chkBoxExtra.CheckedChanged, _
chkBoxMatching.CheckedChanged, _
chkBoxFour.CheckedChanged
txtBoxAcc.Text = FormatCurrency(HandbagAcc)
End Sub