1

i have a datagridview which are used to display a transaction record. And one of the columns in datagridview is "Total", which is "SubTotal" times with "Quantity".

My question is, how do i gonna make "GrandTotal" by calculating all "Total" in datagridview into textbox?

Here is the screenshot:

enter image description here

if you see in the datagridview above, there is column named "Total", this "Total" was got from "Quantity" times "SubTotal", what i want is i want to calculate the "Total" (Sum all of the "Total" in the column) into textbox.

How do i gonna do that?

I already thought about it, but i cannot came with an idea how do i calculate (sum) the "Total" column in the datagridview into the textbox.

I appreciate your answer. Thank you very much!

Kaoru
  • 2,853
  • 14
  • 34
  • 68
  • 1
    See this similar article http://stackoverflow.com/questions/3779729/how-i-can-show-the-sum-of-in-a-datagridview-column – Leigh Ciechanowski Sep 24 '13 at 12:36
  • 1
    Possible duplicate of [how I can show the sum of in a datagridview column?](https://stackoverflow.com/questions/3779729/how-i-can-show-the-sum-of-in-a-datagridview-column) – Mahmoud Ayman Jan 30 '18 at 13:13

3 Answers3

2

Iterate through each row and find cell which hold the total value. convert this total value to double(any numeric data structure) and calculate grand total by adding each one with previous grand total.

Without Linq

    double result = 0;
    foreach (DataGridViewRow row in DataGridView.Rows)
    {
        result += Convert.ToDouble(row.Cells["Total"].Value);
    }

With Linq

    double result = DataGridView.Rows.Cast<DataGridViewRow>().Sum(row => Convert.ToDouble(row.Cells["Total"].Value));
Hossain Muctadir
  • 3,546
  • 1
  • 19
  • 33
0

if you are binding a List or DataTable then just simply use LINQ's SUM method

TalentTuner
  • 17,262
  • 5
  • 38
  • 63
0

// You can use it in the click event of button

str = "YOUR SQL QUERY";
objCom = new SqlCommand(str, objCon);
objDataAdapter = new SqlDataAdapter(objCom);
objDataSet = new DataSet();
objDataAdapter.Fill(objDataSet, "TABLE NAME");
dataGridView2.DataMember = "TABLE NAME";
dataGridView2.DataSource = objDataSet;
dataGridView2[3, dataGridView2.Rows.Count - 1].Value = "Total";
dataGridView2.Rows[dataGridView2.Rows.Count - 1].Cells[3].Style.ForeColor =     Color.White;
dataGridView2.Rows[dataGridView2.Rows.Count - 1].Cells[3].Style.BackColor = Color.Green;
dataGridView2.Rows[dataGridView2.Rows.Count - 1].Cells[4].Style.ForeColor = Color.White;
double sum = 0;
for (int row = 0; row < dataGridView2.Rows.Count; row++)
{
  sum = sum + Convert.ToDouble(dataGridView2.Rows[row].Cells[4].Value);
} 
dataGridView2.Rows[dataGridView2.Rows.Count - 1].Cells[4].Value = sum.ToString();
MAHESH
  • 1