Calculate Sum of Values From a DataGridView in VB.NET.

Posted by Initiotech under Others category on | Views : 43095
This Sample Demonstrates how to Calculate Sum of Values From a DataGridView column.

You can use this code in many scenarios.
Like Calculating Total Products From a Particular Category etc.
In This code we will calculate points of an individual Candidate.

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim tot As Integer = 0
For i As Integer = 0 To DataGridView1.RowCount - 1
If DataGridView1.Rows(i).Cells(1).Value = txtName.Text Then
tot += DataGridView1.Rows(i).Cells(2).Value
End If
If tot = 0 Then
MessageBox.Show("No Records Found")
End If
txtTotal.Text = tot
End Sub

In the Sample Code I have used a Dataset you can use the same code if you are working with a database.
Note * : Do Not Forget to change the index of the columns you want to calculate.

Regards Hefin Dsouza

Comments or Responses

Posted by: Ozzi on: 10/27/2012 Level:Starter | Status: [Member] | Points: 10
great work
how can we add the result to the report?

Posted by: Vdanquah on: 12/15/2012 Level:Starter | Status: [Member] | Points: 10
i try the codes in my project but it is not work with my required column
i have Datagridview to be
Date | ID | Quantity | Amount
11/12/12 2 4 120
12/12/12 3 3 80

and i want to generate the sum for all the columns total Amount

TotalAmount = 120+80 = (200)

Login to post response