Click here to Skip to main content
15,892,072 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
int sum = 0;
          for (int i=0 ; i < dataGridView1.Rows.Count; ++i)
          {
              sum += Convert.ToInt32(dataGridView1.Rows[i].Cells[3]);
          }

          MessageBox.Show(sum.ToString());


What I have tried:

int sum = 0;
          for (int i=0 ; i < dataGridView1.Rows.Count; ++i)
          {
              sum += Convert.ToInt32(dataGridView1.Rows[i].Cells[3].Value);
          }

          MessageBox.Show(sum.ToString());
Posted
Updated 6-Mar-18 10:21am
Comments
cvogt61457 6-Mar-18 13:54pm    
What value are you getting?
Are you sure your values are all numeric?
Do any values contain a decimal point?
Are you getting an exception instead?
Are you debugging the code and watching what is happening?
2011999 6-Mar-18 20:50pm    
Numeric Values
all values are numeric
no decimal points
I got Exception
i Debug the code.i got Exception {"Object reference not set to an instance of an object."}

My first guess is that the values may contain non-numeric data.
Try this
double sum = 0;
for (int i=0 ; i < dataGridView1.Rows.Count; ++i)
{
    double value = 0.0;
    if (double.TryParse(dataGridView1.Rows[i].Cells[3].Value.ToString(), out value))
    {
        sum += value;
    }
}
MessageBox.Show(sum.ToString());
 
Share this answer
 
Check this:
C#
var result = dataGridView1.Rows.OfType<DataGridViewRow>()
    .Where(x=> x.Cells[3]!=null)
    .Sum();;
MessageBox.Show(result.ToString());
 
Share this answer
 

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

  Print Answers RSS
Top Experts
Last 24hrsThis month


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