I create a table in SQL Server Management Studio with this code:
CREATE TABLE contact(
ID INT IDENTITY NOT NULL,
FIRSTNAME VARCHAR(100),
LASTNAME VARCHAR(100)
)
and in C# I used this code:
SqlConnection sc = new SqlConnection("Data Source=.\\SQLSERVER; Initial Catalog=BOSS; Integrated Security=TRUE");
SqlDataAdapter sd = new SqlDataAdapter();
sd.InsertCommand = new SqlCommand("INSERT INTO contact VALUES(@ID, @FIRSTNAME, @LASTNAME)");
sd.InsertCommand.Parameters.Add("@ID", SqlDbType.Int).Value = textBox1.Text;
sd.InsertCommand.Parameters.Add("@FIRSTNAME", SqlDbType.VarChar).Value = textBox2.Text;
sd.InsertCommand.Parameters.Add("@LASTNAME", SqlDbType.VarChar).Value = textBox3.Text;
sc.Open();
sd.InsertCommand.ExecuteNonQuery();
sc.Close();
but when I add the values to the database I get the error:
"ExecuteNonQuery: Connection property has not been initialized"
and I fixed it by adding sc
to my first insertcommand
, but when I run the program I got another error :
An explicit value for the identity column in table 'contact' can only be specified when a column list is used and IDENTITY_INSERT is ON.
using
statement. – OdedDataAdapter
instead of aCommand
directly? – Oded