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

时间:2015-01-10 18:19:03

标签: vb.net listview

我正在尝试获取“ListView”第2列中所有当前值的总和。 我一直得到一个“空值”例外:

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)

2 个答案:

答案 0 :(得分:0)

ListView要注意的一点是,SubItem(0)是指ListViewItem,因此SubItem(1)会引用第一个实际的子项。所以你的索引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

答案 1 :(得分:0)

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)