1

我正在尝试制作一个收银机窗口表单(如下图所示),我知道我想多了,但我对 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

在此处输入图像描述

4

1 回答 1

0

首先,您需要筛选所有输入以确保用户无法输入任何会导致错误的内容。对于简单的收银机,您需要确保数字、减号和可能的回车键有效。就您的数学而言,在这种情况下,您需要在运行总计中保留一个变量,然后当您添加和减去您的值并使用该值更新您的余额 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
于 2012-10-09T04:17:01.800 回答