2017-10-20 35 views
-1

See pic。但是,当我选择第二项,它只是显示第一行的值,但是当我选择它显示了它的正确value.Anyway的第一个项目,这里是我的代码:第二个项目当我加入所有价格栏,它工作完全正常不显示正确的值

Private Sub btnttotal_Click(sender As Object, e As EventArgs) Handles btnttotal.Click 

     Dim totalPrice As Integer = 0 
     Dim i As Integer = 0 
     Do While (i < ListView1.SelectedItems.Count) 
      totalPrice = (totalPrice + Convert.ToInt32(ListView1.Items(i).SubItems(2).Text)) 
      i = (i + 1) 
      txttotal.Text = totalPrice 
     Loop 


    End Sub 
+0

'当我添加所有列'我怀疑你的意思是*行*。但是,代码添加了行0到“ListView1.SelectedItems.Count - 1”,只有2行,是第一行。请阅读[问]并参加[旅游] – Plutonix

回答

0

试试这个:

Private Sub btnttotal_Click(sender As Object, e As EventArgs) Handles btnttotal.Click 

    Dim totalPrice As Integer = 0 
    Dim i As Integer = 0 
    Do While (i < ListView1.SelectedItems.Count) 
     totalPrice = (totalPrice + Convert.ToInt32(ListView1.SelectedItems(i).SubItems(2).Text)) 
     i = (i + 1) 
     txttotal.Text = totalPrice 
    Loop 

End Sub 

如果你看一下上面的解决方案,计算总,只有被选中的值应该考虑到。但是你正在计算列表框中所有行的这一行totalPrice = (totalPrice + Convert.ToInt32(ListView1.Items(i).SubItems(2).Text))。所以,当你选择第二行,你DO WHILE循环只有一次的选择行一个,你的计算是从开始采摘的价值观和100是第一个值,并将其与该停止。我希望你明白这个错误。

如果你想高效,简单地做计算,我建议这样的:

Dim totalPrice As Integer = 0 
For Each item As ListViewItem In ListView1.SelectedItems.Cast(Of ListViewItem)() 
    totalPrice += Convert.ToInt32(item.SubItems(2).Text) 
Next 

txttotal.Text = totalPrice 
0

你是混合了所有这些项目的选定项目的索引。 ListView1.SelectedItemsListView1.Items是两个不同的集合。

如果将刚刚得到的总和这样

Dim totalPrice As Integer = ListView1.SelectedItems _ 
    .Cast(Of ListViewItem)() _ 
    .Sum(Function(item) Convert.ToInt32(item.SubItems(2).Text)) 

此枚举集合SelectedItems更容易上,无需使用任何索引。

要avoi使用索引,你也可以用做每个循环

Dim totalPrice As Integer = 0 
For Each item As ListViewItem In ListView1.SelectedItems.Cast(Of ListViewItem)() 
    totalPrice += Convert.ToInt32(item.SubItems(2).Text) 
Next 

而不是用一个按钮的点击事件,您还可以通过使用SelectedIndexChanged事件ListView的upate总价文本框。它会自动更新。

Private Sub ListView1_SelectedIndexChanged(ByVal sender As Object, _ 
     ByVal e As System.EventArgs) _ 
    Handles ListView1.SelectedIndexChanged 

    Dim totalPrice As Integer = 0 
    For Each item As ListViewItem In ListView1.SelectedItems.Cast(Of ListViewItem)() 
     totalPrice += Convert.ToInt32(item.SubItems(2).Text) 
    Next 
    txttotal.Text = CType(totalPrice, String) 
End Sub 
相关问题