我正在尝试制作一个收银机窗口形式(看起来如下图所示),我知道我正在过度思考这个但是我对vb很新,真的很困惑。但它只需要添加和减去余额。我需要帮助找出如何在这里进行数学计算,比如因为用户将输入所有值,我们如何预测他们将在代码中输入什么?
这是我到目前为止所拥有的:
Public Class frmCashRegister
Dim Total As Decimal
Dim Subtract As Decimal
Dim Balance As Decimal
Private Sub btnAdd_Click(sender As System.Object, e As System.EventArgs) Handles btnAdd.Click
txtBalance.Text = FormatCurrency(Val(txtAmount.Text))
End Sub
Private Sub txtBalance_TextChanged(sender As System.Object, e As System.EventArgs) Handles txtBalance.TextChanged
If (txtBalance.Text < 0) Then
MsgBox("Transaction resulted in negative balance, please try again!")
End If
End Sub
Private Sub txtAmount_KeyPress(sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtAmount.KeyPress
If Asc(e.KeyChar) <> 8 Then
If Asc(e.KeyChar) < 48 Or Asc(e.KeyChar) > 57 Then
e.Handled = True
End If
End If
End Sub
End Class
答案 0 :(得分:0)
首先,您需要筛选所有输入,以确保用户无法输入任何可能导致错误的内容。在简单的收银机的情况下,您需要确保数字,减去添加和可能的输入键工作。至于你的数学,你需要在这种情况下保持一个变量与你的运行总数平衡,然后当你添加和减去你的值并用Value更新你的余额TextBox时,你将更新这个变量。这是关于如何做到这一点的想法。
Dim Total As Decimal
Dim Subtract As Decimal
Dim Balance As Decimal
Private Sub btnAdd_Click(sender As System.Object, e As System.EventArgs) Handles btnAdd.Click
Balance += Decimal.Parse(txtAmount.Text) 'Same as Balance = Balance + Decimal.Parse(txtAmount.Text)
txtBalance.Text = FormatCurrency(Balance)
txtAmount.Text = ""
End Sub
Private Sub btnSubtract_Click(sender As System.Object, e As System.EventArgs) Handles btnSubtract.Click
Balance -= Decimal.Parse(txtAmount.Text) 'Same as Balance = Balance - Decimal.Parse(txtAmount.Text)
txtBalance.Text = FormatCurrency(Balance)
txtAmount.Text = ""
End Sub
Private Sub txtAmount_KeyPress(sender As System.Object, e As System.Windows.Forms.KeyPressEventArgs) Handles txtAmount.KeyPress
If Asc(e.KeyChar) <> 8 AndAlso Asc(e.KeyChar) <> &H2E Then
If Asc(e.KeyChar) = &H2B OrElse Asc(e.KeyChar) = &HD Then
e.Handled = True
btnAdd.PerformClick()
ElseIf Asc(e.KeyChar) = &H2D Then
e.Handled = True
btnSubtract.PerformClick()
ElseIf Asc(e.KeyChar) < 48 Or Asc(e.KeyChar) > 57 Then
e.Handled = True
End If
End If
End Sub