I have a button on a web page that I just need a little help with some extra code. I think I need a TRY, CATCH statement?, this is what I have so far:
I have a simple web page that has a button which at the moment when pressed enables the user to add data to a DB table via a stored procedure. Once this button is pressed a pop up message box is displayed to let the user know the data has been passed. The user then needs to press the ‘OK’ button within this message box which then directs them to the home page of the site. This works fine.
The code for this is here:
Protected Sub btnAddRawData_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAddRawData.Click
'database conn, this is linked to the web config file .AppSettings
Using dbconnection As New SqlConnection(ConfigurationManager.AppSettings("dbconnection"))
dbconnection.Open()
'command to state the stored procedure and the name of the stored procedure
Using dbcommand As SqlCommand = dbconnection.CreateCommand
With dbcommand
.CommandType = CommandType.StoredProcedure
.CommandText = "RawData_Insert"
'simply execute the query
dbcommand.ExecuteNonQuery()
'Code to make a pop up work. It enables us to use and call the function
'located on the main Rawdata.aspx page.
Dim cs As ClientScriptManager = Page.ClientScript
Dim csname1 As String = "PopupScript"
Dim cstype As Type = Me.GetType()
Dim cstext1 As New StringBuilder()
cstext1.Append("success();")
cs.RegisterStartupScript(cstype, csname1, cstext1.ToString())
'redirect to the main home page
Response.Redirect("~/default.aspx?")
End With
End Using
End Using
End Sub
As I don’t want the user to enter duplicate records in the database (This could be done by the user navigating back to the page where the btnAddRawData_Click is located and pressing it again.), I have created a UNIQUE INDEX named ‘DupRecords’ to stop the user from commiting this data more than once that day.
When I run the web page now I get the following message in my browser:
Cannot insert duplicate key row in object 'dbo.GasRawData' with unique index 'DupRecords'. The statement has been terminated.
The solution I think, is to add a TRY, CATCH statement into the btnAddRawData_Click code. Can anyone point me in the right direction and help me put here as I am new to programming and don’t have much experience in this area.
Regards Betty.
You could prevent the user from going back to previous page by using a session
variable that is cleared on successful completion of the stored procedure.
Then check for the session variable when you page loads - if it is not set then response.redirect
to the home page?