Calculating The Sum of values from DataGridView

This Sample Demonstrates how to Calculate Sum of Values From a

DataGridView.


You can use this code in many scenarios.
Like Calculating Sales From a Particular sales man etc.
In This code we will calculate marks of an individual Student.


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
Next
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.

Download The Full Application With Source Code
Regards Hefin Dsouza


Attachments

  • Download Sample Application (27629-101611-TotalFromDataGrid.rar)
  • Comments

    Author: Ahmed03 Aug 2010 Member Level: Bronze   Points : 2

    thank you so MUCH... Mr. Hefin Dsouza .... I was looking for this tip n actually I am working in C# so I did it in c# way n it's working definitely :D

    here is c# Code if SOMEONE would need it 1 day ;-)

    WITHIN ANY EVENT OR METHOD just type this

    {

    int tot = 0;
    for ( int i = 0; i < DataGridViews1.RowCount; i++ )
    {
    tot += Convert.ToInt32(DataGridView1.Rows[i].Cells[7].Value);
    Lbl_Total.Text = tot.ToString();
    }

    if ( tot == 0)
    {
    Lbl_Total.Text = "0";
    }

    }

    Author: Ahmed03 Aug 2010 Member Level: Bronze   Points : 2

    thank you so MUCH... Mr. Hefin Dsouza .... I was looking for this tip n actually I am working in C# so I did it in c# way n it's working definitely :D

    here is c# Code if SOMEONE would need it 1 day ;-)

    WITHIN ANY EVENT OR METHOD just type this

    {

    int tot = 0;
    for ( int i = 0; i < DataGridViews1.RowCount; i++ )
    {
    tot += Convert.ToInt32(DataGridView1.Rows[i].Cells[7].Value);
    Lbl_Total.Text = tot.ToString();
    }

    if ( tot == 0)
    {
    Lbl_Total.Text = "0";
    }

    }



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: