2017-06-21 114 views
0

如何計算列中所有值的總和並將其顯示在label.content中。計算列中值的總和

創建柱:

Dim c7 As New DataGridTextColumn() 
    c7.Header = "Iznos" 
    c7.Width = 100 
    c7.Binding = New Binding("Iznos") 
    gridRacun.Columns.Add(c7) 

類來創建項目:

Class Item 
Private _Cijena As String 
Private _Rabat As String 
Private _PC As String 
Private _Iznos As String 



Property Kolicina() As Integer 
    Get 
     Return _Kolicina 
    End Get 
    Set(ByVal value As Integer) 
     Me._Kolicina = value 
    End Set 
End Property 
Property Cijena() As Decimal 
    Get 
     Return _Cijena 
    End Get 
    Set(ByVal value As Decimal) 
     Me._Cijena = value 
    End Set 
End Property 

Property Iznos() As Decimal 
    Get 
     Return _Iznos 
    End Get 
    Set(ByVal value As Decimal) 
     Me._Iznos = Me._Kolicina * Me.Cijena 
    End Set 
End Property 
End Class 

添加項目到數據網格:

 Dim item = New Item With {.Cijena = Globals.cijenaTempG, .Rabat = Globals.rabatG, .PC = 1.0, .Iznos = 1.0} 
    gridRacun.Items.Add(item) 

我要計算一個名爲 「Iznos」 列的SUM並將其顯示在標籤上。內容

+0

將項目添加到「DataGrid」時,可以計算總和。 –

回答

0

我想你可以遍歷DataGridView中的行和計算的總和

dim sum = 0 
for each row as datagridviewrow in gricRacun.rows 
dim cellValue as double 
if not double.tryparse(row.cells(c7.index).value,cellValue) then cellValue = 0 
sum += cellValue 
next row 

你可以觸發它的文字改變事件等事件,並指定其中你想

0

列綁定到物品的財產。總結這些屬性並將其暴露給視圖,而不是關注網格本身。

' Calculate the sum (using Linq). 
Dim sum = gridRacun.Items.OfType(Of Item)().Sum(Function(item) item.Iznos) 
' Update the label. 
labelSum.Content = sum 

現在剩下的就是確定何時觸發計算。嘗試收聽集合更改的時間,或者更新任何項目的有關屬性。