Compute Method in DataTable

I have a DataTable, bound to a DataGridView for data entry.  As a row is entered, I'd like to populate a label with the running total of the "Total Cost" column.  

I've found documentation and have code that is working, BUT, it seems that the compute method is always one row behind.  User enters row(0), the label does not populate, then after user enters rows(2), going into Row(3), the label.text is populated with the total of Row(0) only.

When I call DataTable.AcceptChanges, the datatable is cleared.  

Any thoughts?

Here is code I'm using:

Private Sub DG_Labor_CellValueChanged(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DG_Labor.CellValueChanged
    If e.ColumnIndex = 9 Then
                    Try
                        Me.Calc_Labor_Totals()
                    Catch ex As Exception
                        MsgBox("Couldn't Calculate the total Labor Sum")
                    End Try
    End If
End Sub

Private Sub Calc_Labor_Totals()
        Dim result = dt_LaborInfo.Compute("sum(Labor_Total_Cost)", "")
        Me.lbl_Labor_Totals.Text = result.ToString()
    End Sub
LVL 1
tobin46Asked:
Who is Participating?
 
Carlos VillegasFull Stack .NET DeveloperCommented:
Hi, use the DataBindingComplete event instead:
    Private Sub DG_Labor_DataBindingComplete(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewBindingCompleteEventArgs) Handles DG_Labor.DataBindingComplete
        Try
            Me.Calc_Labor_Totals()
        Catch ex As Exception
            MsgBox("Couldn't Calculate the total Labor Sum")
        End Try
    End Sub

Open in new window


And you can avoid exceptions raised by null values by using something like this:
    Private Sub Calc_Labor_Totals()
        Dim result As Object = dt_LaborInfo.Compute("sum(Labor_Total_Cost)", "")
        Me.lbl_Labor_Totals.Text = IIf(Not result Is DBNull.Value, result.ToString(), "")
    End Sub

Open in new window


I hope this help.
0
 
tobin46Author Commented:
Perfect.  Worked great!
0
 
Carlos VillegasFull Stack .NET DeveloperCommented:
Glad to help buddy!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.