如何显示错误消息是记录(主键)已存在

时间:2014-08-06 13:04:52

标签: vb.net

导入System.Data 导入System.Data.SqlClient 部分类别注册     继承System.Web.UI.Page     将myConn变暗为SqlConnection     Dim cmd As SqlCommand

Dim sqlstring, ide, name, fname, cty, cpassw As String

Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load

End Sub

Protected Sub submitbtn_Click(sender As Object, e As EventArgs) Handles submitbtn.Click
    ide = idbox.Text
    name = namebox.Text
    fname = fatherbox.Text
    cty = countrybox.Text

    cpassw = confirmpass.Text
    myConn = New SqlConnection("Data Source=(localdb)\v11.0;Initial Catalog=C:\USERS\DREAM THEATER\DOCUMENTS\VISUAL STUDIO 2012\WEBSITES\WEBAPP\APP_DATA\DATAAJIT.MDF;Integrated Security=True")
    myConn.Open()

    sqlstring = " INSERT INTO Test (Id,name,father,country,pass) VALUES (" + ide + ",'" + name + "','" + fname + "','" + cty + "','" + cpassw + "')"
    cmd = New SqlCommand(sqlstring, myConn)
    cmd.ExecuteNonQuery()
    MsgBox("Added Successfully !!!!!", MsgBoxStyle.Information, "Insert !!")
    myConn.Close()
    Response.Redirect("Login.aspx")


End Sub

以上是我的代码。 我必须添加什么代码行以及在哪里?

1 个答案:

答案 0 :(得分:1)

尝试使用try catch来捕获异常。

例如:

   Protected Sub submitbtn_Click(sender As Object, e As EventArgs) Handles submitbtn.Click
        ide = idbox.Text
        name = namebox.Text
        fname = fatherbox.Text
        cty = countrybox.Text

        cpassw = confirmpass.Text

        Try

        myConn = New SqlConnection("Data Source=(localdb)\v11.0;Initial Catalog=C:\USERS\DREAM THEATER\DOCUMENTS\VISUAL STUDIO 2012\WEBSITES\WEBAPP\APP_DATA\DATAAJIT.MDF;Integrated Security=True")
        myConn.Open()

        sqlstring = " INSERT INTO Test (Id,name,father,country,pass) VALUES (" + ide + ",'" + name + "','" + fname + "','" + cty + "','" + cpassw + "')"
        cmd = New SqlCommand(sqlstring, myConn)
        cmd.ExecuteNonQuery()
        MsgBox("Added Successfully !!!!!", MsgBoxStyle.Information, "Insert !!")
        myConn.Close()
            Response.Redirect("Login.aspx")

        Catch ex As Exception
            MsgBox("An error occured: " & ex.Message)
        End Try


    End Sub

这将显示一个消息框,其中包含发生的异常消息。