vb.net 获取VB.Net中ListView特定列中所有值的总和
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27879594/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get the sum of all values in a specific column of a ListView in VB.Net
提问by Chip Datamaker
I am trying to get the sum of all the current values in column 2 of a "ListView". I keep getting a "null value" exception for :
我正在尝试获取“ListView”第 2 列中所有当前值的总和。我不断收到“空值”异常:
Me.ListView1.GetItemAt(ListView1.FocusedItem.Index, 2).Text)
and I also tried this which still threw the exception:
我也试过这个仍然抛出异常:
Dim X As Double = CDbl(Form1.ListView1.Items.Item(Index).SubItems(2).Text)
The Code block that is giving me the exception is:
给我例外的代码块是:
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)
采纳答案by ??ssa P?ngj?rdenlarp
A thing to keep in mind with the ListView, is that SubItem(0)refers to the ListViewItem, so SubItem(1)will reference the first actual subitem. So your index of 2 is actually referring to what appears in the third "column".
需要记住的ListView, 是SubItem(0)指ListViewItem,因此SubItem(1)将引用第一个实际子项。所以你的索引 2 实际上是指第三个“列”中出现的内容。
You define TotalValueinside a Sub which makes it a local variable - it only resides there. Assuming the Total is of some interest, the procedure should be a Function returning that value. Also, your loop skips the first item, is a little wordy, and the existence of Form1.indicates you are not using explicit form references (use Meto reference the current form instance):
您TotalValue在 Sub 内部定义,使其成为局部变量 - 它仅驻留在那里。假设对 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
回答by Waruna Manjula
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)

