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)

        If InStr(UCase(Trim(txtSQL.Text)), "SELECT") > 0 Then

            DataGridView1.DataSource = BindingSource1

            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)

        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
        SAdapter.Update(SDtable)
    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
