Imports System.Data.SqlClient
Public Class Form1
    Private SqlCon As New SqlConnection
    Private SAdapter As New SqlDataAdapter
    Private SDtable As New DataTable
    Private Sub btnConnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConnect.Click
        Dim conString As String = txtConString.Text & ""

        SqlCon.ConnectionString = conString
        SqlCon.Open()

        txtList.Text = "接続しました" & vbCrLf
        btnConnect.Enabled = False
        btnExec.Enabled = True
        btnClose.Enabled = True
        btnUpdate.Enabled = True
    End Sub

    Private Sub btnExec_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExec.Click
        Dim command As SqlCommand = New SqlCommand(Trim(txtSQL.Text), SqlCon)
        Dim i As Integer

        If InStr(UCase(Trim(txtSQL.Text)), "SELECT") > 0 Then
            txtKList.Text = ""
            DataGridView1.DataSource = BindingSource1
            If chkKey.Checked Then
                SAdapter.MissingSchemaAction = MissingSchemaAction.AddWithKey
            End If
            SAdapter.SelectCommand = command
            Dim commandBuilder As New SqlCommandBuilder(SAdapter)
            SDtable.Clear()
            Try
                SAdapter.Fill(SDtable)
            Catch ex As SqlException
                _txtList.Text = ex.Message
                Exit Sub
            End Try
            BindingSource1.DataSource = SDtable
            DataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader)
            txtList.Text = "結果を取得しました" & vbCrLf
            If chkKey.Checked Then
                Dim DBcolArr() As DataColumn
                DBcolArr = SDtable.PrimaryKey
                For i = 0 To DBcolArr.GetUpperBound(0)
                    txtKList.Text = txtKList.Text & DBcolArr(i).ColumnName & vbCrLf
                Next
            End If
        Else
            Try
                command.ExecuteNonQuery()
                txtList.Text = "更新しました" & vbCrLf
            Catch ex As SqlException
                _txtList.Text = ex.Message
                Exit Sub
            End Try
        End If
    End Sub


    Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdate.Click
        Try
            SAdapter.Update(SDtable)
            txtList.Text = "更新しました" & vbCrLf
        Catch ex As SqlException
            _txtList.Text = ex.Message
            Exit Sub
        End Try
    End Sub

    Private Sub btnClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClose.Click
        SqlCon.Close()
        txtList.Text = "切断しました" & vbCrLf
        btnConnect.Enabled = True
        btnExec.Enabled = False
        btnClose.Enabled = False
        btnUpdate.Enabled = False
    End Sub

End Class
