2017-10-20 2 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

'모든 열을 추가 할 때 나는 행 *을 의미한다고 의심합니다. 그러나이 코드는'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)). 따라서 두 번째 행을 선택하면 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은 두 가지 컬렉션입니다.

경우 직접 인덱스를 사용하지 않고 단지이 컬렉션 SelectedItems을 열거이

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

같은 합계를 얻을하는 것이 더 쉽습니다.

각 루프에 대해 당신은 또한 함께 할 수있는 인덱스를 사용하여

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 
관련 문제