i have created that table on my sql server :
create table Empolyee(
ESSN int not null,
EFirstName varchar(20) not null ,
ELastName varchar(20) not null,
EJob varchar(20),
EBDate date,
ESalary int,
primary key(ESSN));
and in C# i try to add data to database using that code :
SqlConnection sqc = new SqlConnection("Data Source=.\\;Initial Catalog=DB;Integrated Security=True");
SqlDataAdapter da = new SqlDataAdapter();
DataSet ds = new DataSet();
da.SelectCommand = new SqlCommand("INSERT INTO Empolyee VALUES (@ESSN,@EFirstName,@ELastName,@EJob,@EBDate,@ESalary)", sqc);
da.SelectCommand.Parameters.Add("@ESSN", SqlDbType.Int).Value = textBox1.Text;
da.SelectCommand.Parameters.Add("@EFirstName", SqlDbType.VarChar).Value = textBox2.Text;
da.SelectCommand.Parameters.Add("@ELastName", SqlDbType.VarChar).Value = textBox3.Text;
da.SelectCommand.Parameters.Add("@EJob", SqlDbType.VarChar).Value = textBox4.Text;
da.SelectCommand.Parameters.Add("@EBDate", SqlDbType.Date).Value = maskedTextBox1.Text;
da.SelectCommand.Parameters.Add("@ESalary", SqlDbType.Int).Value = textBox5.Text;
// open connection
sqc.Open();
// excute the command
da.InsertCommand.ExecuteNonQuery();
// close connection
sqc.Close();
i get that error when i run : Object reference not set to an instance of an object or System.NullReferenceException: Object reference not set to an instance of an object.
you haven’t assigned anything to
da.InsertCommand– instead you have put anINSERTcommand intoda.SelectCommand… just change all references fromda.SelectCommandtoda.InsertCommandin the code you show in your question:BTW you don’t need any
SqlDataAdapterorDataSetto execute anINSERT– it can be done withSqlConnectionandSqlCommandonly.