How to get a total in selected columns based on the column name in datagridview using VB.net

Arrow 1 Reputation point
2022-10-13T13:19:19.227+00:00

Hi!,
I am using a data grid view as a data entry table and I want to get the total for each row for the columns with same HeaderText as shown in below. Can anyone help me with this.

250096-image.png

Developer technologies | VB
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. LesHay 7,141 Reputation points
    2022-10-13T14:05:00.913+00:00

    Hi
    Here is one way. I have used a DataTable named 'dt' for the data and the two last columns have expressions which will automatically calculate the sum of appropriate columns. The sample data are just random numbers, but manual input will be auto calculated too.
    This is a stand alone example - just use a new project to try it out.

    250124-111.png

    Public Class Form1  
    	Dim dt As New DataTable("freddy")  
    	Private Sub Form1_Load(senderAsObject, eAsEventArgs) Handles MyBase.Load  
    		With dt  
    			.Columns.Add("ID", GetType(Integer))  
    			.Columns.Add("A1-QTY", GetType(Integer))  
    			.Columns.Add("B1-QTY", GetType(Integer))  
    			.Columns.Add("A2-QTY", GetType(Integer))  
    			.Columns.Add("B2-QTY", GetType(Integer))  
    			.Columns.Add("TOTAL A-QTY", GetType(Integer), "[A1-QTY] + [A2-QTY]")  
    			.Columns.Add("TOTAL B-QTY", GetType(Integer), "[B1-QTY] + [B2-QTY]")  
      
    			'sample data  
    			Dim r As New Random  
    			For i As Integer = 1 To 10  
    				.Rows.Add(i, r.Next(100) + 1, r.Next(100) + 1, r.Next(100) + 1, r.Next(100) + 1)  
    			Next  
    		End With  
    		DataGridView1.DataSource = dt  
    	End Sub  
    End Class  
    

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.