Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C#
private void button2_Click(object sender, EventArgs e)
       {
           for (int i = 0; i <= dataGridView1.Rows.Count; i++)
           {
               int sum = 0 ;
 
               sum = sum + Convert.ToInt32(dataGridView1.Rows[i].Cells[i].Value);
               textBox2.Text = Convert.ToString(sum);
           }
       }
Posted 31-Oct-12 1:28am
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

Of course your code wont work because simply you telling the program to get the sum of the first row first cell and second row second cell etc...
and in one point you will get an error if your rows are more than your columns
you need to add another for loop to loop over the cells in each row this is how its going to work
 
Hope this helped
  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

The better way to do this would be to
 
1. have a form level variable to store the sum,
2. initialize it to 0
3. and then in RowDatBound event add the current rows value into this member variable.
 
When the grid is bound this varable will contain the sum.
 
4. you can put this value in a textbox in unlod event.
  Permalink  
Comments
zeshanazam at 31-Oct-12 15:09pm
   
new in c#, i didn't get your solution.
zeshanazam at 31-Oct-12 15:25pm
   
got an error "Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index"

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

  Print Answers RSS
0 OriginalGriff 215
1 George Jonsson 175
2 Kornfeld Eliyahu Peter 159
3 PIEBALDconsult 110
4 Richard MacCutchan 85
0 OriginalGriff 6,080
1 DamithSL 4,648
2 Maciej Los 4,087
3 Kornfeld Eliyahu Peter 3,624
4 Sergey Alexandrovich Kryukov 3,294


Advertise | Privacy | Mobile
Web04 | 2.8.141220.1 | Last Updated 31 Oct 2012
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100