0

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");
            }



        }

        
    }
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Zass
  • 19
  • 2
  • Related: https://stackoverflow.com/questions/68962208/exception-thrown-system-data-sqlclient-sqlexception-in-system-data-sqlclient –  Aug 28 '21 at 09:57
  • Does this answer your question? [What is a PRIMARY KEY](https://stackoverflow.com/questions/29708849/what-is-a-primary-key) and [What is the difference b/w Primary Key and Unique Key](https://stackoverflow.com/questions/2973420/what-is-the-difference-b-w-primary-key-and-unique-key/2973573) and [difference between primary key and unique key](https://stackoverflow.com/questions/9565996/difference-between-primary-key-and-unique-key) –  Aug 28 '21 at 10:06
  • 3
    C# is relaying a SQL error, basically it thinks you are trying to insert a duplicate record based on the primary key (unique identifier) the error is deliberate as SQL will not let you insert a duplicate primary key, mostly primary keys are autogenerated by the DB and are normally integers, perhaps RegistrationNumber needs to be removed. you can view the primary key in SQL – fuzzybear Aug 28 '21 at 10:07
  • [Primary key Definition](https://en.wikipedia.org/wiki/Primary_key) • [Database Management System Tutorial](https://www.tutorialspoint.com/dbms/index.htm) • [Database Management System Course](https://www.guru99.com/dbms-tutorial.html) –  Aug 28 '21 at 10:08
  • @OlivierRogier Thank you sir, But I know what is a primary key. I am having trouble with the Duplication of pk. I cant find whats the wrong the code. – Zass Aug 28 '21 at 10:11
  • @saj Sir, should I remove the primary key then? – Zass Aug 28 '21 at 10:12
  • @Zass "*I know what is a primary key*" => So why such a question while saying "*I am a beginner*" ... ? –  Aug 28 '21 at 10:12
  • @Zass You know very well where you have typed the number 456785. The field that you try to set with that value doesn't allow a duplicate. You need to not execute an insert if there is already that value. So you need to read before to write. – Steve Aug 28 '21 at 10:13
  • @OlivierRogier I am a beginner to the c# coding sir. – Zass Aug 28 '21 at 10:13
  • 3
    The error has nothing to do with C# but with the schema of your table. – Steve Aug 28 '21 at 10:14
  • 1
    @Zass The problem here has absolutely nothing to do with C# ... it seems to me ... right? You try to insert a record with a PK that exists. It's a SQL problem. Asking a question about the exception is a knowledge problem, I think ... therefore the suggested links. But if you say you *know* ... it's fantastic. –  Aug 28 '21 at 10:14
  • @OlivierRogier Ok Sir, Noted. Thank you. – Zass Aug 28 '21 at 10:16
  • 2
    @Zass no don't remove the primary key, first you need to find it, using SQL management studio or similar, right click table and view the properties, then remove it from your SQL query, check if the primary key is autogenerated if not don't remove, just use a number that's does not exist. – fuzzybear Aug 28 '21 at 10:16
  • @saj Thank you sir, I did exactly what u said. Seems to be it was the problem I had. – Zass Aug 28 '21 at 10:23

0 Answers0