For Each Dgv As DataGridViewRow In Me.DataGridView1.Rows
Dim cn As New SqlConnection()
If cn.State = ConnectionState.Open Then cn.Close()
cn.ConnectionString = Form1.ConString
cn.Open()
Dim cm As New SqlCommand
Dim sql As String = ""
sql = "insert into SelectCourse (CustomerID, CourseID) values (@CustomerID, @CourseID)"
cm.CommandText = sql
cm.CommandType = CommandType.Text
cm.Connection = cn
cm.Parameters.Clear()
cm.Parameters.Add("@CustomerID", SqlDbType.NVarChar, 15).Value = TxtCusSearch.Text
cm.Parameters.Add("@CourseID", SqlDbType.NChar, 8).Value = Dgv.Cells("CourseID").Value
cm.ExecuteNonQuery()
MsgBox("บันทึกข้อการจองคอร์สเรียบร้อยแล้ว")
Next
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim cn As New SqlConnection()
If cn.State = ConnectionState.Open Then cn.Close()
cn.ConnectionString = Form1.ConString
cn.Open()
Dim cm As New SqlCommand
Dim sql As String = ""
sql = "insert into SelectCourse (CustomerID, CourseID) values (@CustomerID, @CourseID)"
cm.CommandText = sql
cm.CommandType = CommandType.Text
cm.Connection = cn
For i As Integer = 0 To DataGridView1.Rows.Count - 1
cm.Parameters.Add("@CustomerID", SqlDbType.NVarChar, 15).Value = TxtCusSearch.Text
cm.Parameters.Add("@CourseID", SqlDbType.NChar, 8).Value = DataGridView1.Rows(i).Cells(0).Value
cm.ExecuteNonQuery()
Next
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim cn As New SqlConnection(Form1.ConString)
'Dim tr As New SqlTransaction()
Dim tr As SqlTransaction
Dim success As Boolean = True;
Dim errorMessage As String = String.Empty
If cn.State <> ConnectionState.Open Then cn.Open()
tr = cn.BeginTransaction(IsolationLevel.ReadCommitted)
For i As Integer = 0 To DataGridView1.Rows.Count - 1
Dim sql As String = "INSERT INTO [SelectCourse] ([CustomerID], [CourseID]) VALUES (@CustomerID, @CourseID)"
Dim cm As New SqlCommand(sql, cn)
cm.Parameters.AddWithValue("@CustomerID", TxtCusSearch.Text)
cm.Parameters.AddWithValue("@CourseID", DataGridView1.Rows(i).Cells(0).Value)
cm.Transaction = tr;
Try
cm.ExecuteNonQuery()
Catch ex As Exception
success = False
errorMessage = ex.Message
Exit For
End Try
Next
If success Then
tr.Commit()
cn.Close()
MsgBox("บันทึกข้อมูลการจองคอร์สเรียบร้อยแล้ว")
Else
tr.Rollback()
cn.Close()
MsgBox("เกิดข้อผิดพลาดไม่สามารถจองคอร์สได้ จากสาเหตุ: " & errorMessage)
End If
End Sub