应该在VBNET中使用什么错误处理

问题描述 投票:0回答:1

这是我保存BTN的代码

 Private Sub SaveBtn2_Click(ByVal sender As System.Object, ByVal e As 
 System.EventArgs) Handles SaveBtn2.Click
    Dim dt As New DataTable
    Dim adapter As New SqlDataAdapter


    Dim con As String = "Data Source = HCA-ISD03\SQLEXPRESS; Initial Catalog = QMS_HCA; User ID=qs; Password=ZAQ!2wsx; MultipleActiveResultSets=True"
    Dim conn As New SqlConnection(con)

    conn.Open()

    cmd.Connection = conn
    cmd.CommandText = "spSaveAddNewAlerts"
    cmd.CommandType = CommandType.StoredProcedure


    cmd.Parameters.AddWithValue("@MESSAGE", Message.Text)

    cmd.Parameters.AddWithValue("@DCREATED", DateTimePicker1.Value)

    cmd.Parameters.AddWithValue("@CREATEDBY", Createdby.Text)

    cmd.ExecuteNonQuery()





    If Message.Text = "" Then

        MessageBox.Show("Message cannot be empty, fill in before proceeding", _
                        "User Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        Message.Focus()


    Else
        MessageBox.Show("Application Restarting..", _
                        "User Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        Message.Focus()
        Application.Restart()

        conn.Close()

    End If

    MsgBox("Saved, Updating Database..")
    Application.Restart()


End Sub

如何中断要保存在数据库中的数据。即使我有消息错误,我已经关闭了我的连接。数据仍然存在于数据库中。请帮忙。谢谢!

sql-server vb.net error-handling save
1个回答
0
投票

为什么不在存储过程调用之前放置您的验证,如果您有验证错误,只返回单击处理程序?

Private Sub SaveBtn2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveBtn2.Click

    'Check this first, before running the stored procedure!
    If Message.Text = "" Then

        MessageBox.Show("Message cannot be empty, fill in before proceeding",
                    "User Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        Message.Focus()
        Return 'Exit the method!
    End If

    Dim dt As New DataTable
    Dim adapter As New SqlDataAdapter

    Dim con As String = "Data Source = HCA-ISD03\SQLEXPRESS; Initial Catalog = QMS_HCA; User ID=qs; Password=ZAQ!2wsx; MultipleActiveResultSets=True"
    Dim conn As New SqlConnection(con)

    conn.Open()

    cmd.Connection = conn
    cmd.CommandText = "spSaveAddNewAlerts"
    cmd.CommandType = CommandType.StoredProcedure

    cmd.Parameters.AddWithValue("@MESSAGE", Message.Text)

    cmd.Parameters.AddWithValue("@DCREATED", DateTimePicker1.Value)

    cmd.Parameters.AddWithValue("@CREATEDBY", Createdby.Text)

    cmd.ExecuteNonQuery()

    conn.Close()

    MsgBox("Saved, Updating Database..")
    Application.Restart()
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.