我正在尝试获取“ 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)
请注意ListView
,SubItem(0)
指的是ListViewItem
,因此SubItem(1)
将引用第一个实际的子项。因此,您的索引2实际上是指第三个“列”中出现的内容。
您可以TotalValue
在Sub中定义它,使其成为局部变量-它仅驻留在此处。假设总计是有意义的,则该过程应该是一个返回该值的函数。同样,您的循环跳过了第一项,有点罗word,并且存在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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句