Reputation: 73
I would like to insert a record into my RDV Table.
This is the query creation of my table
CREATE TABLE [dbo].[RDV] (
[idRdv] INT NOT NULL,
[objet] NVARCHAR (50) NULL,
[objectif] NVARCHAR (50) NULL,
[DateRdv] DATETIME NULL,
[commentaire] NVARCHAR (50) NULL,
[archive] NVARCHAR (50) NULL,
[idClient] INT NULL,
[idUser] INT NULL,
[idResultat] INT NULL,
CONSTRAINT [PK_RDV] PRIMARY KEY CLUSTERED ([idRdv] ASC),
FOREIGN KEY ([idClient]) REFERENCES [dbo].[Client] ([idClient]),
FOREIGN KEY ([idUser]) REFERENCES [dbo].[User] ([idUser]),
FOREIGN KEY ([idResultat]) REFERENCES [dbo].[Resultat] ([idResultat]);
and this is my code of insert
public RDV()
{
InitializeComponent();
textBox3.Visible = false;
label7.Visible = false;
}
private void btnAdd_Click(object sender, EventArgs e)
{
Random rdm = new Random();
int num = rdm.Next(5, 2000);
textBox3.Text = num.ToString();
string cmdStr = "Insert into RDV (idRdv,idUser,idClient,objet,objectif,DateRdv,commentaire) select @idRdv,@idUser,@idClient,@objet,@objectif,@DateRdv,@commentaire from RDV, Client, [User] where RDV.idClient = Client.idClient and RDV.idUser = [User].idUser ";
SqlConnection con = new SqlConnection("Data Source=ADMIN-PC\\SQLEXPRESS;Initial Catalog=timar;Integrated Security=True");
SqlCommand cmd = new SqlCommand(cmdStr, con);
cmd.Parameters.AddWithValue("@idRdv", textBox3.Text);
cmd.Parameters.AddWithValue("@idUser", (comboBox1.SelectedValue));
cmd.Parameters.AddWithValue("@idClient", (comboBox2.SelectedValue));
cmd.Parameters.AddWithValue("@objet", textBox1.Text);
cmd.Parameters.AddWithValue("@objectif", textBox2.Text);
cmd.Parameters.AddWithValue("@DateRdv", dateTimePicker1.Value.ToString());
cmd.Parameters.AddWithValue("@commentaire", textBox4.Text);
con.Open();
int LA = cmd.ExecuteNonQuery();
Console.WriteLine("Ligne ajoutée: {0}", LA);
And,the field idRdv , i want to add it but should be hidden and Random like in the code above.
When , I run my project , it shows me an error Violation of PRIMARY KEY " PK_RDV ". Can not insert duplicate key in object ' dbo.RDV ". Value of Duplicate Key:1505 (this the value of idRdv)
Pleaaaaseee, help me. How should I correct it.
Thanks in advance
Upvotes: 1
Views: 151
Reputation: 1396
You are using the ID with Random
. As your table ID column is containing Primary Key Constraint
it may get this error.
Either you check that the random number generated is not exist in the table before insert. Or use a method to get Max(ID)+1
and set this as new ID
Upvotes: 1