Violation of PRIMARY KEY constraint 'PK_SES'. Cannot insert duplicate key in object 'dbo.SES'. The duplicate key value is (456785)

924 views Asked by At

I am a beginner in C#. So please help me with this issue.

Exception thrown: 'System.Data.SqlClient.SqlException' in System.Data.SqlClient.dll An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.SqlClient.dll Violation of PRIMARY KEY constraint 'PK_SES'. Cannot insert duplicate key in object 'dbo.SES'. The duplicate key value is (456785).

Please note that I am not a programmer, I am just a student who was given a school project.

Here's the code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.Sql;
using System.Data.SqlClient;


namespace DiTEC_Assignment
{
    public partial class SES : Form
    {
        SqlConnection conn;
        SqlCommand cmd;
        SqlDataAdapter sda;

        public SES()
        {
            InitializeComponent();
        }

        private void btnInsert_Click(object sender, EventArgs e)
        { 
            using var conn = new SqlConnection(@"Data Source=TS-G5\SQLEXPRESS;Initial Catalog=EsoftProj;Integrated Security=True");
            using var cmd = new SqlCommand("INSERT INTO SES([Registration Number], [Student Name], [Date of Birth], Gender, [Contact Number], [Course enrolled in]) VALUES (@RegistrationNumber,@StudentName,@DateOfBirth,@Gender,@ContactNumber,@CourseEnrolledIn)", conn);

            conn.Open();
            cmd.Parameters.Add("@RegistrationNumber", SqlDbType.Int).Value = Convert.ToInt32(RegNumTB.Text);
            cmd.Parameters.Add("@StudentName", SqlDbType.Text).Value = StudentNameTB.Text;
            cmd.Parameters.Add("@DateOfBirth", SqlDbType.Date).Value = DoBPick.Value.Date;
            cmd.Parameters.Add("@Gender", SqlDbType.Text).Value = GMale.Checked ? "M" : "F";
            cmd.Parameters.Add("@ContactNumber", SqlDbType.Int).Value = Convert.ToInt32(ContactNumTB.Text);
            cmd.Parameters.Add("@CourseEnrolledIn", SqlDbType.Text).Value = CourseEnrSel.GetItemText(CourseEnrSel.SelectedItem);
            cmd.ExecuteNonQuery();

            if(cmd.ExecuteNonQuery()>0)
            {
                MessageBox.Show("Record inserted");
            }
            else
            {
                MessageBox.Show("Record failed");
            }



        }

        
    }
}
0

There are 0 answers