This function is in a Class file in App_Code folder
Public Shared Function CRUD(ByVal _sql As String, ByVal _parameterNames() As String, ByVal _parameterVals() As String) As Integer
Dim _noOfRowsAffected As Integer
Dim _connection As SqlConnection = Global.Connection.GetDbConnection()
Dim _command As New SqlCommand(_sql, _connection)
Try
If _parameterNames IsNot Nothing Then
For i = 0 To _parameterNames.Length - 1
_command.Parameters.AddWithValue(_parameterNames(i), _parameterVals(i))
Next
End If
_noOfRowsAffected = _command.ExecuteNonQuery()
Catch ex As Exception
'MsgBox(ex.Message)
_noOfRowsAffected = -1
Finally
If _connection.State = ConnectionState.Open Then
_connection.Close()
_connection.Dispose()
_command.Dispose()
End If
End Try
Return _noOfRowsAffected
End Function
This code is in aspx.vb page
Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
Dim _parameterNames(6), _parameterVals(6) As String
_parameterNames(0) = "@Name"
_parameterVals(0) = txtCoachingName.Text
_parameterNames(1) = "@Address"
_parameterVals(1) = txtCoachingAddress.Text
_parameterNames(2) = "@Mob1"
_parameterVals(2) = txtCoachingMob1.Text
_parameterNames(3) = "@Mob2"
_parameterVals(3) = txtCoachingMob2.Text
_parameterNames(4) = "@LLine"
_parameterVals(4) = txtCoachingLLine.Text
_parameterNames(5) = "@Established"
_parameterVals(5) = ddlCoachingEstablished.SelectedValue
_parameterNames(6) = "@DemoVideo"
_parameterVals(6) = txtCoachingDemoVideo.Text
_parameterNames(7) = "@Password"
_parameterVals(7) = txtCoachingPassword.Text
Try
DataAccess.CRUD("UPDATE CoachingDetails SET Name=@Name,Address=@Address,Mob1=@Mob1,Mob2=@Mob2,L_Line=@LLine,Established=@Established,Demo_Video=@DemoVideo,Password=@Password,Step_Completed='True',Time_Stamp='" & Date.Now & "'", _parameterNames, _parameterVals)
Catch ex As Exception
End Try
Now i want to catch the Primary Key Violation exception in my aspx.vb page..but i do not get the exception in the aspx.vb page as the error is caught by the class function.So, how do i get the exception from the class file to the aspx.vb file??
End Sub
Rethrow. (http://www.selfelected.com/rethrow/)
Since you don’t do anything in the catch just skip it.
To make the code nicer read up on Using. With Using you can have the compiler insert the Try/Finally implicitly for you. The code will be something like:
Please note that I made all your variables local. This might not be possible for you since you know a lot more about your code than I do… (but the code suggested that your variables where class variables but you treated them as local anyway.)
Also check out Dapper. Dapper is what Stack overflow runs on. It is a nice small lib for making writing sql calls easier to write and read.