Laura M

Laura M

  • NA
  • 1
  • 7.6k

Visual Studio 2010 set Identity_insert table on/off

Jan 9 2014 8:34 AM
Hello!

I was having some trouble with this error, but i added the command, and now i receive another error (Connection property has not been initialized.). Please, check out my code:
 
 
protected void btnAdd_Client(object sender, System.EventArgs e)
{
SqlConnection con = new SqlConnection(@"Data Source=JOHN-PC\SQLEXPRESS;Initial Catalog=subiect1;Integrated Security=True");
try
{
con.Open();
SqlCommand command = new SqlCommand("SET IDENTITY_INSERT Clienti ON");
command.ExecuteNonQuery();
SqlCommand cmd = new SqlCommand("insert into Clienti(ID, Nume, Prenume, Data_Nasterii, Adresa_mail) values(@ID, @Nume, @Prenume, @Data_Nasterii, @Adresa_mail)", con);
cmd.Parameters.AddWithValue("@ID", txtID.Text);
cmd.Parameters.AddWithValue("@Nume", txtNume.Text);
cmd.Parameters.AddWithValue("@Prenume", txtPrenume.Text);
cmd.Parameters.AddWithValue("@Data_Nasterii", txtDataNastere.Text);
cmd.Parameters.AddWithValue("@Adresa_mail", txtAdresamail.Text);
int count = cmd.ExecuteNonQuery();
if (count == 1)
lblMsg.Text = "Clientul [" + txtID.Text + "] a fost adaugat!";
else
lblMsg.Text = "Clientul nu a putut fi adaugat!";
}
catch (Exception ex)
{
lblMsg.Text = "Error --> " + ex.Message;
}
finally
{
SqlCommand comm = new SqlCommand("SET IDENTITY_INSERT Clienti OFF");
comm.ExecuteNonQuery();
con.Close();
}
}
 
This is a function which adds new clients in my local database. As you can see, i placed the set_identity commands before and after the actual adding client code. What do i miss here? 
 
 
 
 

Answers (2)