[VB.NET]取得DataGridView欄位變更前與變更後的值

  • 21992
  • 0
  • 2010-08-02

取得DataGridView欄位變更前與變更後的值

在藍色小舖中,有人問 如何取得DataGirdView 欄位變更前與變更後的值,其實可以簡單的透過 DataGirdView 的這兩個事件DataGridView.CellValueChanged 與 DataGridView.CellBeginEdit 達成

CellBeginEdit 發生於選定的儲存格開始編輯模式時,先將欄位內的資料儲存
CellValueChanged 發生於儲存格的值變更時,取得改變後的值
http://msdn.microsoft.com/zh-tw/library/system.windows.forms.datagridview.cellbeginedit(VS.80).aspx
http://msdn.microsoft.com/zh-tw/library/system.windows.forms.datagridview.cellvaluechanged(VS.80).aspx

程式碼

Private Sub DataGridView1_CellValueChanged(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellValueChanged
        ' 取得變更後的值
        If DataGridView1.Rows.Count > 0 Then
            Dim dr As String
            dr = DataGridView1(e.ColumnIndex, e.RowIndex).Value.ToString()
            Label2.Text = "更新欄位後的值為 : " & dr
        End If

    End Sub

    Private Sub DataGridView1_CellBeginEdit(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellCancelEventArgs) Handles DataGridView1.CellBeginEdit
        ' 取得開始編輯時的值
        If DataGridView1.Rows.Count > 0 Then
            Dim dr As String
            dr = DataGridView1(e.ColumnIndex, e.RowIndex).Value.ToString()
            Label1.Text = "編輯欄位前的值為 : " & dr
        End If
    End Sub

執行結果

 

http://www.blueshop.com.tw/board/show.asp?subcde=BRD20090320105558BG8&fumcde=