以前、SqlDataAdapterにより抽出したデータをDataGridViewに表示する方法をご紹介しましたが、今回はDataGridViewに表示したデータを変更したり削除したり、または追加して、それをSQL Serverに反映させる方法をご紹介します。
ちなみに、今回も開発ツールは、Visual Studio Community 2015 を使っています。

まず、フォームにこのようにコントロールを貼り付け、下記のように名前を付けてください。
| コントロール | 名前 |
|---|---|
| DataGridView | dgv |
| Button | buttonView |
| Button | buttonOK |
| Button | buttonCancel |
| Button | buttonApply |
ソースは下記のようになります。
VB
Imports System.Data.SqlClient
Public Class Form1
Private Cnn As SqlConnection
Private Cmd As SqlCommand
Private InsCmd As SqlCommand
Private UpdCmd As SqlCommand
Private DelCmd As SqlCommand
Private Dta As SqlDataAdapter
Private Txn As SqlTransaction
Private Dts As DataSet = New DataSet
Private cancelFlag As Boolean = False
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim ConnectionString As String = "Data Source=localhost\MSSQLSERVER;Initial Catalog=TESTDB;Integrated Security=True"
Cnn = New SqlConnection(ConnectionString)
Cnn.Open()
Cmd = New System.Data.SqlClient.SqlCommand
InsCmd = New System.Data.SqlClient.SqlCommand
UpdCmd = New System.Data.SqlClient.SqlCommand
DelCmd = New System.Data.SqlClient.SqlCommand
Dta = New System.Data.SqlClient.SqlDataAdapter
SetDataSource
'適用ボタン非活性
Me.buttonApply.Enabled = False
End Sub
Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
Me.Validate()
Try
'キャンセルボタンの場合、保存しないで終了。
If (cancelFlag = True) Then
Return
End If
If Dts.HasChanges Then
Dim result As DialogResult
result = MessageBox.Show("データが変更されています。保存しますか?", "質問", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question)
Select Case (result)
Case DialogResult.Yes
Apply()
Case DialogResult.No
Case DialogResult.Cancel
e.Cancel = True
Case Else
e.Cancel = True
End Select
Return
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
If (Not (Dta) Is Nothing) Then Dta.Dispose()
If (Not (DelCmd) Is Nothing) Then DelCmd.Dispose()
If (Not (UpdCmd) Is Nothing) Then UpdCmd.Dispose()
If (Not (InsCmd) Is Nothing) Then InsCmd.Dispose()
If (Not (Cmd) Is Nothing) Then Cmd.Dispose()
If (Not (Dts) Is Nothing) Then Dts.Dispose()
If (Not (Cnn) Is Nothing) Then Cnn.Close()
End Try
End Sub
Private Sub dgv_CellValueChanged(sender As Object, e As DataGridViewCellEventArgs) Handles dgv.CellValueChanged
'セルの値が変更されたら適用ボタンを活性化
Me.buttonApply.Enabled = True
End Sub
Private Sub dgv_UserDeletedRow(sender As Object, e As DataGridViewRowEventArgs) Handles dgv.UserDeletedRow
'行削除が行われたら適用ボタンを活性化
Me.buttonApply.Enabled = True
End Sub
Private Sub buttonView_Click(sender As Object, e As EventArgs) Handles buttonView.Click
SetDataSource()
End Sub
Private Sub buttonOK_Click(sender As Object, e As EventArgs) Handles buttonOK.Click
'OK
Apply()
Me.Close()
End Sub
Private Sub buttonCancel_Click(sender As Object, e As EventArgs) Handles buttonCancel.Click
'キャンセル
cancelFlag = True
Me.Close()
End Sub
Private Sub buttonApply_Click(sender As Object, e As EventArgs) Handles buttonApply.Click
'適用
Apply()
SetDataSource()
Me.buttonApply.Enabled = False
End Sub
Private Sub Apply()
Try
If Dts.HasChanges Then
'トランザクションを開始
Txn = Cnn.BeginTransaction
Dta.UpdateCommand.Transaction = Txn
Dta.DeleteCommand.Transaction = Txn
Dta.InsertCommand.Transaction = Txn
'データ更新
Dta.Update(Dts, "T_Animals")
'トランザクションをコミット
Txn.Commit()
End If
Catch
Txn.Rollback()
Throw
Finally
If (Not (Txn) Is Nothing) Then
Txn.Dispose()
End If
End Try
End Sub
Private Sub SetDataSource()
Try
'Selectコマンドの作成
Cmd.Connection = Cnn
Cmd.CommandType = CommandType.Text
Cmd.CommandText = "SELECT [ID], [Name], [Type] FROM [T_Animals] ORDER BY [ID]"
'追加コマンドの作成
InsCmd.Connection = Cnn
InsCmd.CommandType = CommandType.Text
InsCmd.CommandText = "INSERT INTO [T_Animals] ([ID], [Name], [Type]) VALUES (@ID, @Name, @Type)"
InsCmd.Parameters.Clear()
InsCmd.Parameters.Add("@ID", SqlDbType.Int, 4, "ID")
InsCmd.Parameters.Add("@Name", SqlDbType.NVarChar, 50, "Name")
InsCmd.Parameters.Add("@Type", SqlDbType.NVarChar, 50, "Type")
'更新コマンドの作成
UpdCmd.Connection = Cnn
UpdCmd.CommandType = CommandType.Text
UpdCmd.CommandText = "UPDATE [T_Animals] SET [ID] = @ID, [Name] = @Name, [Type] = @Type WHERE [ID] = @ID"
UpdCmd.Parameters.Clear()
UpdCmd.Parameters.Add("@ID", SqlDbType.Int, 4, "ID")
UpdCmd.Parameters.Add("@Name", SqlDbType.NVarChar, 50, "Name")
UpdCmd.Parameters.Add("@Type", SqlDbType.NVarChar, 50, "Type")
'削除コマンドの作成
DelCmd.Connection = Cnn
DelCmd.CommandType = CommandType.Text
DelCmd.CommandText = "DELETE FROM [T_Animals] WHERE [ID] = @ID"
DelCmd.Parameters.Clear()
DelCmd.Parameters.Add("@ID", SqlDbType.Int, 4, "ID")
If Dts.Tables.Contains("T_Animals") Then
Dts.Tables("T_Animals").Clear()
End If
'各コマンドの設定
Dta.SelectCommand = Cmd
Dta.InsertCommand = InsCmd
Dta.UpdateCommand = UpdCmd
Dta.DeleteCommand = DelCmd
'抽出したデータをデータセットに格納
Dta.Fill(Dts, "T_Animals")
'列クリア
Me.dgv.Columns.Clear()
'DataGridViewのデータソースを設定
Me.dgv.DataSource = Nothing
Me.dgv.DataSource = Dts.Tables("T_Animals")
'適用ボタン非活性
Me.buttonApply.Enabled = False
Catch
Throw
End Try
End Sub
End Class

「OK」または「適用」ボタンで変更した内容がデータベースへ反映されます。
C#のソースはこちらをご覧ください。
スポンサーリンク