Dim index As Integer
Dim choice As String
Dim total As Integer
total = 0
index = NumericUpDown1.Value
Dim arr(4) As Integer
arr(0) = 10
arr(1) = 5
arr(2) = 21
arr(3) = 33
If index > 0 Then
choice = (Combobox1.SelectedItem.ToString + " x " + NumericUpDown1.Value.ToString)
ListBox1.Items.Add(choice)
CheckedListBox1.Items.Add(choice)
total += arr(Combobox1.SelectedIndex) * index
TotalLabel.Text = total.ToString()
Else
MsgBox("error.")
End If
我可以计算单项选择的总数,但不能累计总和。 代码怎么了?
现状: 第1步: 选择arr(0),index = 2 总数= 20
第2步: 选择arr(2),index = 1 总计= 21
正确的情况: 第1步: 选择arr(0),index = 2 总数= 20
第2步: 选择arr(2),index = 1 总数= 41
答案 0 :(得分:0)
您需要一个全局变量或一个带有公共变量的类。您应该创建一个Transaction
类来存储有关事务的数据,并可能创建一个Product
类来存储有关产品的数据。你输入的内容取决于你,但我会从这样的事情开始:
Public Class Transaction
Private _productsList As List(of Product)
Private _transationNumber As Integer
'...more stuff...
'you'll want to remember what products are in your "cart" for the transaction
Public Property ProductsList As List(of Product)
'your get/set accessors
End Property
Public Property TransactionNumber As Integer
'your get/set accessors
End Property
Public Property TotalTransactionCost() As Double
Get
'this will sum of the prices of all of the products you have stored in your
'list of products for this transaction
Return _productsList.Sum(product => product.Price)
End Get
End Property
Public Sub New()
'...constructor stuff
End Sub
Public Sub AddProductToTransaction(byval product)
_productsList.Add(product)
End Sub
End Class
Public Class Product
Private _price As Double
Private _productName As String
Private _UPC As String
Public Property Price() As Double
'your get/set accessors
End Property
Public Property ProductName() As String
'your get/set accessors
End Property
Public UPC As String () As String
'your get/set accessors
End Property
Public Sub New()
'constructor stuff
End Sub
End Class
这些是一些可以帮助您入门的类shell。如果您对制作产品非常认真,那么这是朝着正确方向迈出的一步。如果您要编写代码,请以正确的方式编写代码。
如果您只是在寻找一个快速而肮脏的解决方案,您可以声明一个全局变量并保持运行总和。在开始新交易之前,别忘了清除它。
你会想做类似的事情:
Private TransactionCost As Double
在您所有方法的外表单中。
同样,我会建议第一种处理事情的方法。你需要至少这两个类,他们肯定会更真实地为真正的产品充实。
我希望这有助于解答您的问题。如果确实如此,请用upvote打我并接受答案。欢迎来到SO。