Click here to Skip to main content
15,911,035 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
these code work with me to sum one column in datagrideview but i want to sum multi columns in datagrideview

C#
decimal sum1 = 0, sum2 = 0;
            for (int i = 0; i < dgw.RowCount; i++)
            {
                // we only sum the first and third column as an example
                sum1 += Convert.ToDecimal(dgw.Rows[i].Cells[4].Value);
                sum2 += Convert.ToDecimal(dgw.Rows[i].Cells[5].Value);
            }
            // add the total row
            string[] totalrow = new string[] { sum1.ToString(), "", sum2.ToString() };
            dgw.Rows.Add(totalrow);
            // add a rowheadertitle
            dgw.RowHeadersWidth = 60;
            dgw.Rows[dgw.RowCount - 1].HeaderCell.Value = "Total"; 


What I have tried:

these code work with me to sum one column in datagrideview but i want to sum multi columns in datagrideview
Posted
Updated 6-Jan-18 23:54pm
Comments
Karthik_Mahalingam 6-Jan-18 1:15am    
so what is the issue ?
Dotnet_Dotnet 6-Jan-18 1:19am    
decimal sum1 = 0, sum2 = 0,sum3 =0;
for (int i = 0; i < dgw.RowCount; i++)
{
// we only sum the first and third column as an example
sum1 += Convert.ToDecimal(dgw.Rows[i].Cells[4].Value);
sum2 += Convert.ToDecimal(dgw.Rows[i].Cells[5].Value);
sum3 = sum3 + (sum1+ sum2);
}
// add the total row
string[] totalrow = new string[] { sum1.ToString(), "", sum2.ToString() };
dgw.Rows.Add(totalrow);
// add a rowheadertitle
dgw.RowHeadersWidth = 60;
dgw.Rows[dgw.RowCount - 1].HeaderCell.Value = "Total";

1 solution

these code work with me to sum one column in datagrideview but i want to sum multi columns in datagrideview

Are you sure?
You want to sum the first and third column , but you refer to Cells[4] and Cells[5]
C#
sum1 += Convert.ToDecimal(dgw.Rows[i].Cells[4].Value);
sum2 += Convert.ToDecimal(dgw.Rows[i].Cells[5].Value);


Also, the way you add new row is wrong:
C#
string[] totalrow = new string[] { sum1.ToString(), "", sum2.ToString() };

The size of array have to be equal to the count of cells!

For example:
C#
// Set the column header names.
dataGridView1.Columns[0].Name = "Recipe";
dataGridView1.Columns[1].Name = "Category";
dataGridView1.Columns[2].Name = "Main Ingredients";
dataGridView1.Columns[3].Name = "Rating";

// Populate the rows.
//ColNo                              0          1           2           3
string[] row1 = new string[] { "Meatloaf", "Main Dish", "ground beef", "**" };
dataGridView1.Rows.Add(row1);


For further details, please see: DataGridView.Rows Property (System.Windows.Forms)[^]
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900