2015-01-10 33 views
1

我想獲得「ListView」的列2中的所有當前值的總和。 我不斷收到一個「空值」例外:在VB.Net中獲取ListView的特定列中的所有值的總和

Me.ListView1.GetItemAt(ListView1.FocusedItem.Index, 2).Text) 

,我也試過這種仍然拋出異常:

Dim X As Double = CDbl(Form1.ListView1.Items.Item(Index).SubItems(2).Text) 

的代碼塊是給我的例外是:

Public Sub getSubtotal() 
    Dim Index As Integer 
    Dim TotalValue As Double 

    For Index = 1 To Form1.ListView1.Items.Count - 1 
     Dim X As Double = CDbl(Form1.ListView1.Items.Item(Index).SubItems(2).Text) 
     TotalValue = TotalValue + X 
    Next 

    MsgBox(TotalValue) 
+1

'子項(0)'實際上是Item.Text,所以'SubItems(2)'將成爲第三個「列」 – Plutonix

回答

0

需要注意的一點是ListViewSubItem(0)是指ListViewItem,所以SubItem(1)會r參考第一個實際的子項目。所以你的索引2實際上是指出現在第三個「列」中的內容。

您在Sub中定義了TotalValue,它使它成爲一個局部變量 - 它只存在於那裏。假設Total有一些興趣,程序應該是返回該值的函數。此外,你的循環跳過的第一個項目,就是有點羅嗦,和Form1.的存在表明您不使用顯式的形式引用(使用Me來引用當前表單實例):

' Optional ToDo: pass a int value indicating which "column" to add up 
Public Function GetSubTotal() As Decimal 

    Dim TotalValue As Decimal 
    Dim tmp As Decimal 

    ' arrays and collections start at index(0) not (1) 
    ' OP code would skip the first item 
    For n as Integer = 0 To ListView1.Items.Count - 1 

     ' ToDo: Not all items must have the same number of SubItems 
     ' should also check SubItems Count >= 1 for each item 
     ' try to get the value: 
     If Decimal.TryParse(ListView1.Items(n).SubItems(1).Text, tmp) Then 
       TotalValue += tmp 
     End If   
    Next 

    Return TotalValue 
End Function 
相關問題