2017-10-20 18 views
-1

See picすべての価格列を追加すると、正常に機能します。しかし、私はちょうどその2番目の項目を選択すると、それだけで最初の行の値を示したが、その後、私はそれが正しいvalue.Anywayを示して最初の項目を選択すると、ここに私のコードです:これを試してみてくださいリストビューで選択された2番目の項目に正しい値が表示されない

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

'すべての列を追加すると、あなたは*行*を意味すると思われます。しかし、コードは 'ListView1.SelectedItems.Count - 1'を介して行0を追加しており、2行だけでその最初の行が追加されています。 [ask]を読んで[tour] – 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))。したがって、2番目の行を選択すると、DO WHILEは選択された行が1であるため1回だけループし、計算は開始から値を取り上げており、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は2つの異なるコレクションです。

ちょうどこの

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

のような合計を取得するために容易になるだろう場合これは、任意のインデックスを使用せずに直接収集SelectedItemsを列挙します。

各ループのためにあなたはまたでそれを行うことができますインデックスを使用して

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

代わりのボタンのクリックイベントを使用してavoiするために、あなたもListViewSelectedIndexChangedイベントを使用して合計金額をテキストボックスを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 
関連する問題