We're a community of 1076K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,075,886 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

Sum of cells in DataGridView

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.

4
Contributors
4
Replies
19 Hours
Discussion Span
4 Months Ago
Last Updated
7
Views
Question
Answered
LD Company
Light Poster
30 posts since Aug 2012
Reputation Points: 0
Solved Threads: 0
Skill Endorsements: 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()
TnTinMN
Practically a Master Poster
640 posts since Jun 2012
Reputation Points: 418
Solved Threads: 148
Skill Endorsements: 13

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
Zick Technology
Junior Poster
183 posts since Dec 2012
Reputation Points: 0
Solved Threads: 2
Skill Endorsements: 3

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

Gé48
Junior Poster in Training
63 posts since Apr 2010
Reputation Points: 11
Solved Threads: 10
Skill Endorsements: 0

Thanks!

All answers are correct! :D

LD Company
Light Poster
30 posts since Aug 2012
Reputation Points: 0
Solved Threads: 0
Skill Endorsements: 0
Question Answered as of 4 Months Ago by Gé48, TnTinMN and Zick Technology

This question has already been solved: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
 
© 2013 DaniWeb® LLC
Page rendered in 0.0722 seconds using 2.69MB