【VB.NET】DataGridViewの編集があったすべてのセルに対して操作を行う

編集前の値の退避

VB
    Private Sub DataGridView1_CellBeginEdit(sender As Object, e As DataGridViewCellCancelEventArgs) Handles DataGridView1.CellBeginEdit
        '編集前の値を保持
        G_BeforeVal = DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value
    End Sub

編集前と値が異なる場合、DataTableに格納

VB
    Private Sub DataGridView1_CellEndEdit(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellEndEdit

        '編集後の値
        Dim AfterVal = DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value
        If G_BeforeVal <> AfterVal Then
            Dim NewRow = G_dt_After.NewRow
            NewRow("Name") = DataGridView1.Rows(e.RowIndex).Cells(DataGridView1.Columns("Name").Index).Value
            NewRow("Schedule") = DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value
            G_dt_After.Rows.Add(NewRow)
        End If

    End Sub

変更があったすべてのセル値を表示する

VB
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        '変更された値を表示
        For Each row In G_dt_After.Rows
            Debug.WriteLine(row("Name") & "" & row("Schedule"))
        Next

DataTableの作成

VB
 Public G_BeforeVal As String
 Public G_dt_Before As New DataTable
 Public G_dt_After As New DataTable
 Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

     With G_dt_Before
         .Columns.Add("Name", GetType(String))
         .Columns.Add("Schedule", GetType(String))
         .Rows.Add("David", "会議")
         .Rows.Add("Steve", "休暇")
         .Rows.Add("Kevin", "出張")
         .Rows.Add("Alice", "出張")
     End With

     With DataGridView1
         .DataSource = G_dt_Before
         .AllowUserToAddRows = False
         .Columns("Name").ReadOnly = True
     End With

     G_dt_After = G_dt_Before.Clone

 End Sub

コメント

タイトルとURLをコピーしました