Running total columns in DataGridView

SeanPress 186 Reputation points
2024-07-13T23:42:00.3966667+00:00

Hi,

I have a DataGridView with 4 columns & I am trying make the last 2 columns running totals, calculated by checking if the Type column value is A or B, then adding the Quantity column progressively as new rows are added. Please see table below to demonstrate what I am trying to achieve. I have added the VB code I am using below, when I use this I am getting a running total for both types in both columns, i.e. both running total columns are adding all the Vol column values all the way down regardless of whether they are type A or B. Can anyone help sort my code to differentiate between the two types & have each running total column only add the Vol for the appropriate Type?

Type Vol Running Total A Running Total B
A 3 3
A 2 5
B 3 3
A 4 9
B 5 8

Dim valT As Double = 0

Dim valA As Double = 0

 

        For Each row As DataGridViewRow In DataGridView1.Rows

            If row.Cells(“colTyp”).Value = (“A”) Then

                For i As Integer = 0 To DataGridView1.Rows.Count - 1

                    valA += DataGridView1.Rows(i).Cells("colVol").Value

                    DataGridView1.Rows(i).Cells("colRunA").Value = valA

                Next

            ElseIf row.Cells(“colTyp”).Value = (“B”) Then

                    For i As Integer = 0 To DataGridView1.Rows.Count - 1

                        valB += DataGridView1.Rows(i).Cells("colVol").Value

                        DataGridView1.Rows(i).Cells("colRunB").Value = valB

                    Next

            End If

        Next

VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,659 questions
{count} votes