2012-08-23 45 views
0

在我的表單上我有一個標籤(lblBalance),我有一個從Access數據庫填充的DGV。如果我添加,刪除或更新一行,如何刷新標籤文本以反映新的餘額?如何在datagridview中的某行更改時更新標籤的文本?

這是我frmMain代碼至今:

Public Class frmMain 

     Private Sub TransactionsBindingNavigatorSaveItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TransactionsBindingNavigatorSaveItem.Click 
     Me.Validate() 
     Me.TransactionsBindingSource.EndEdit() 
     Me.TableAdapterManager.UpdateAll(Me.CheckingDataSet) 

     End Sub 

     Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 
     'TODO: This line of code loads data into the 'CheckingDataSet.Transactions' table. You can move, or remove it, as needed. 
     Me.TransactionsTableAdapter.Fill(Me.CheckingDataSet.Transactions) 
     lblTotalCredits.Text = BalanceTotal().ToString("c") 
     End Sub 

     Private Function BalanceTotal() As Double 
     Dim tot As Double = 0 
     Dim i As Integer = 0 
     For i = 0 To TransactionsDataGridView.Rows.Count - 1 
      tot = tot + Convert.ToDouble(TransactionsDataGridView.Rows(i).Cells(3).Value) 
     Next i 
     Return tot 
     End Function 
    End Class 
+0

如果您在處理金錢問題,您應該考慮使用Decimal類型而不是Double類型。 – LarsTech

+0

使用DGV事件,比如'DGV.RowsRemoved' – UnLoCo

回答

0

BindingSource的控制有一個ListChanged事件中,你可以嘗試使用更新您的餘額標籤。

Private Sub TransactionsBindingSource_ListChanged(_ 
       sender As Object, _ 
       e As ListChangedEventArgs) _ 
       Handles TransactionsBindingSource.ListChanged 

    lblTotalCredits.Text = BalanceTotal().ToString("c") 

End Sub 
+0

我添加了這段代碼,但現在它在BalanceTotal()函數的這一行中引發了一個InvalidCastException。 tot = tot + Convert.ToDouble(TransactionsDataGridView.Rows(i).Cells(3).Value) 任何想法? – user1618156

+0

@ user1618156單元格中的值是什麼?嘗試使用[Double.TryParse](http://msdn.microsoft.com/en-us/library/994c0zb1(v = vs.100).aspx)而不是'Convert.ToDouble'。既然你有一個數據源,你不應該從網格中獲取這些值,我會直接從數據源中獲取它們。 – LarsTech