Cummulative column in DataGrid View

SeanPress 206 Reputation points
2024-07-09T16:29:44.96+00:00

Hi,

I have a DataGridView with 4 columns & I am trying make the last 2 columns cumulative totals, calculated by checking if the Type column value is Type 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 intend to create a line chart later with the two cumulative columns as separate series. Can anyone help me with VB code to achieve this?

TypeQuantityType A CumulativeType B CumulativeA33A14B44A59A312A315B59B110A722Any help would be much appreciated.

Regards,

Sean

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

Accepted answer
  1. Jiachen Li-MSFT 32,451 Reputation points Microsoft Vendor
    2024-07-10T06:39:22.8166667+00:00

    Hi @SeanPress ,

    You can count the quantities of each type separately in the CellValueChanged event

        Private Sub DataGridView1_CellValueChanged(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellValueChanged
            Dim typeATotal = DataGridView1.Rows.Cast(Of DataGridViewRow)() _
                            .Where(Function(row) Not row.IsNewRow AndAlso row.Cells("Type").Value.ToString() = "A") _
                            .Sum(Function(row) Convert.ToInt32(row.Cells("Quantity").Value))
    
            Dim typeBTotal = DataGridView1.Rows.Cast(Of DataGridViewRow)() _
                            .Where(Function(row) Not row.IsNewRow AndAlso row.Cells("Type").Value.ToString() = "B") _
                            .Sum(Function(row) Convert.ToInt32(row.Cells("Quantity").Value))
    
            If DataGridView1.Rows.Count > 0 Then
                DataGridView1.Rows(0).Cells("Type A Cumulative").Value = typeATotal
                DataGridView1.Rows(0).Cells("Type B Cumulative").Value = typeBTotal
            End If
        End Sub
    
    

    Best Regards.

    Jiachen Li


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.