Can you manipulate data in a datagridview in real time

I need to be able to take the average of the values in a column in a datagridview after rows have been deleted, without affecting the data source.  The code counts the correct number of rows but it takes the average of the data source not the datagridview.
Private Sub ReCalc_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ReCalc.Click
        Dim count As Integer = 0
        Dim total As Double = 0
 
        WSW067DataGridView.EndEdit()
 
 
        For Each row As DataGridViewRow In WSW067DataGridView.Rows
            total += row.Cells(10).Value
        Next
 
        While count < WSW067DataGridView.RowCount
           
            count += 1
 
        End While
        lblCount.Text = count - 1
        lblGoldUsageAverage.Text = total / count

Open in new window

glstackAsked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
Jorge PaulinoConnect With a Mentor IT Pro/DeveloperCommented:
>> The code counts the correct number of rows but it takes the average of the data source not the datagridview.

Can you explain this better ???

Try to do this:

lblGoldUsageAverage.Text = total / WSW067DataGridView.RowCount -1

0
 
Jorge PaulinoIT Pro/DeveloperCommented:
And you don't need this:

While count < WSW067DataGridView.RowCount
         count += 1
End While
0
 
SanclerCommented:
As the code you show is taking the values for the total and the count directly from the DataGridView, I don't see how the result can be anything different from the average of what's shown in the DataGridView.  What am I missing?

And, incidentally, I don't see the need for the loop in lines 12 to 16.  Couldn't you just use

        lblCount.Text = WSW067DataGridView.RowCount - 1

in line 17?


Roger
0
 
SanclerCommented:
Cross-post ;-)
0
 
glstackAuthor Commented:
This is what I ended up using.  Thanks for the help!

Private Sub ReCalc_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ReCalc.Click
        Dim count As Integer
        Dim total As Decimal = 0

        WSW067DataGridView.EndEdit()
       
        For Each row As DataGridViewRow In WSW067DataGridView.Rows
            total += row.Cells(10).Value

        Next

        count = WSW067DataGridView.RowCount - 1
        lblGoldUsageAverage.Text = total / count
0
All Courses

From novice to tech pro — start learning today.