1,105,271 Community Members

Sum of cells in DataGridView

Member Avatar
LD Company
Light Poster
30 posts since Aug 2012
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

How can I get sum of total values from cells in DataGridView? I want it to look like this

Column1 Column2 Column3 Column4
String ---- String ---- String ---- 10
String ---- String ---- String ---- 7
String ---- String ---- String ---- 3
String ---- String ---- String ---- 5

I want to get number 25 (Sum from Column4).

Thanks.

Member Avatar
TnTinMN
Practically a Master Poster
640 posts since Jun 2012
Reputation Points: 418 [?]
Q&As Helped to Solve: 152 [?]
Skill Endorsements: 16 [?]
 
0
 

Give this a try:
Remember that the column nubering is zero index based (Column4 = index 3)

    Dim sum As Int32 = (From dgvrow In DataGridView1.Rows _
                       Select CInt(CType(dgvrow, DataGridViewRow).Cells(3).Value)) _
                       .Sum()
Member Avatar
ImZick
Posting Whiz in Training
201 posts since Dec 2012
Reputation Points: 0 [?]
Q&As Helped to Solve: 4 [?]
Skill Endorsements: 4 [?]
 
0
 

Try this code and put it on a Button

Dim sum As Double = 0
For i = 0 To DatagridView1.RowCount - 1
sum += DatagridView1.Rows(i).Cells("ColumnName").Value() 'put your Column Name here.
Next

TextBox1.text = sum 'the result will display in a TextBox
Member Avatar
Gé48
Junior Poster in Training
76 posts since Apr 2010
Reputation Points: 1 [?]
Q&As Helped to Solve: 14 [?]
Skill Endorsements: 0 [?]
 
0
 

This works for me, even if there is text in one or more of the cells

On Error Resume Next
For i = 0 To DataGridView1.CurrentRow.Index
      sum = sum + DataGridView1.Rows(i).Cells("Column3").Value
Next i

the cells

Member Avatar
LD Company
Light Poster
30 posts since Aug 2012
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

Thanks!

All answers are correct! :D

Question Answered as of 1 Year Ago by ImZick, Gé48 and TnTinMN
You
This question has already been solved: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article