mysterious problem (data no inserting )
I have a little problem which i want to discuss with you.
I writed the following code which is incrementing the id automatically.
But this code working fine till we are inserting he 10th record i.e. emp10.
But when we insert the 11th record, i.e. emp11,it starts throwing the error message:
Voilation of primary key constraint 'PK_EmpRegistration'. Cannot insert duplicate key in object 'EmpRegistration'. The Statement has been terminated.Can you help me how this problem can be rectified.
CODE::::::::::::::::::::::::::
Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
Dim intMaxID As Integer
Dim strID As String
Dim objcommand As SqlCommand = New SqlCommand
Dim maxIDcommand As SqlCommand = New SqlCommand _
("Select MAX(ID) as maxID from EmpRegistration " & _
"Where ID like 'emp%'", objConnection)
'Open the connection, execute the command
objConnection.Open()
Dim maxID As Object = maxIDcommand.ExecuteScalar()
'If the MaxID column is null...
If maxID Is DBNull.Value Then
'Set a default value of 1...
intMaxID = 1
Else
'Otherwise set the strID variable to the value in MaxID...
strID = CType(maxID, String)
'Get the integer part of the string...
intMaxID = CType(strID.Remove(0, 3), Integer)
'Increment the value...
intMaxID = intMaxID + 1
End If
strID = "emp" & intMaxID.ToString
objcommand.Connection = objConnection
objcommand.CommandText = "Insert into EmpRegistration " & _
"(ID, Name, Address, BirthDate, Email, Qualification, PhNo,Experience, " & _
"Reference, JoinDate, Salary) Values (@ID, @Name, @Address, @BirthDate, @Email, " & _
"@Qualification, @PhNo, @Experience, @Reference, @JoinDate, @Salary);"
objcommand.Parameters.Add("@ID", strID)
objcommand.Parameters.Add("@Name", txtEmpName.Text)
objcommand.Parameters.Add("@Address", txtAddress.Text)
objcommand.Parameters.Add("@BirthDate", txtDOB.Text)
objcommand.Parameters.Add("@Email", txtEmail.Text)
objcommand.Parameters.Add("@Qualification", txtQualification.Text )
objcommand.Parameters.Add("@PhNo", txtPhNo.Text)
objcommand.Parameters.Add("@Experience", cboEmpRegistrationExperience.SelectedIndex)
objcommand.Parameters.Add("@Reference", txtReference.Text)
objcommand.Parameters.Add("@JoinDate", txtJoinDate.Text)
objcommand.Parameters.Add("@salary", txtSalary.Text)
Try
objcommand.ExecuteNonQuery()
Catch SqlExceptionErr As SqlException
MessageBox.Show(SqlExceptionErr.Message)
End Try
objConnection.Close()
FillDataSetAndView()
BindFields()
End Sub
:::::::::::::::::::::::::::::::
|