获取 VB.Net 中 ListView 特定列中所有值的总和

Get the sum of all values in a specific column of a ListView in VB.Net

我正在尝试获取 "ListView" 的第 2 列中所有当前值的总和。 我不断收到 "null value" 异常:

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)

关于 ListView 要记住的一点是 SubItem(0) 指的是 ListViewItem,因此 SubItem(1) 将引用第一个实际的子项。所以你的索引 2 实际上指的是第三个 "column".

中出现的内容

您在 Sub 中定义 TotalValue 使其成为局部变量 - 它仅驻留在此处。假设对总计感兴趣,该过程应该是一个返回该值的函数。另外,你的循环跳过了第一项,有点罗嗦, 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
Dim Index As Integer
Dim TotalValue As Double

For Index = 1 To ListView1.ListItems.Count
    TotalValue = TotalValue + ListView1.ListItems(Index).SubItems(2)
Next

 MsgBox(TotalValue)