如果添加记录被取消,则返回添加另一条记录

时间:2017-10-05 11:15:48

标签: sql-server vb.net

当我点击消息框时我遇到了添加记录的问题,我回答是否然后取消它并添加另一条记录但是我没有初始化我的代码谢谢你。

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Try
        Dim reader As SqlDataReader
        conn.Open()
        Dim bday As String
        bday = adyear.Text & "-" & admonth.Text & "-" & adday.Text


        If adfirstname.Text.Length < 2 Then
            MessageBox.Show("Firstname is too short")
        End If

        Dim exist As String
        exist = "select * from record where firstname='" & adfirstname.Text & "'" & " and lastname='" & adlastname.Text & "';"
        cmd = New SqlCommand(exist, conn)
        reader = cmd.ExecuteReader
        If reader.HasRows = True Then
            If MsgBox("THE MEMBER YOU ARE TRYING TO ADD HAS AN SAME FIRSTNAME AND LASTNAME IN THE RECORD DO YOU WISH TO CONTINUE ?", MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
            ElseIf adage.Text < 18 Then
                If MsgBox("The member is less than 18 years old is this an intern?", MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
                    Dim add As String
                    add = "insert into record(firstname,middlename,lastname,birthday,age,jobposition)" & _
                         "values(" & _
                         "'" & adfirstname.Text & "'," & _
                         "'" & admiddlename.Text & "'," & _
                         "'" & adlastname.Text & "'," & _
                         "'" & bday & "'," & _
                         "'" & adage.Text & "'," & _
                         "'" & adjobposition.Text & "');"
                    cmd = New SqlCommand(add, conn)
                    cmd.ExecuteNonQuery()
                    MessageBox.Show("Added Complete")

                Else
                    MsgBox("Action is Terminated")

                    ' code for return to adding and stop the messagebox of the connection has not been initialized


                End If
            End If
        End If

            conn.Close()
    Catch ex As Exception
        MessageBox.Show(ex.Message)
    Finally
        conn.Dispose()
    End Try

End Sub

结束班

1 个答案:

答案 0 :(得分:0)

好吧,因为看起来conn是一个表单级对象,你需要调用

conn = New SqlConnection(<connection string>) 

之前可以使用它来打开连接。鉴于你打电话

conn.Dispose()

要销毁Finally块中的conn实例,似乎你没有长时间保持打开连接。