+ Reply to Thread
Results 1 to 3 of 3

Thread: accessing sql database

  1. #1

    accessing sql database

    in C# i try to add data to database using the below code :

    SqlConnection sqc = new SqlConnection("Data Source=.\\SQLSERVER;Initial Catalog=DataBaseName;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
            // excute the command
            // close connection

    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.
    Last edited by basemhosam; 01-07-2012 at 02:42 AM.

  2. #2
    you haven't assigned anything to da.InsertCommand - instead you have put an INSERT command into da.SelectCommand... just change all references from da.SelectCommand to da.InsertCommand in the code you show in your question:

        da.InsertCommand = new SqlCommand("INSERT INTO Empolyee VALUES (@ESSN,@EFirstName,@ELastName,@EJob,@EBDate,@ESalary)", sqc);
        da.InsertCommand.Parameters.Add("@ESSN", SqlDbType.Int).Value = textBox1.Text;
        da.InsertCommand.Parameters.Add("@EFirstName", SqlDbType.VarChar).Value = textBox2.Text;
        da.InsertCommand.Parameters.Add("@ELastName", SqlDbType.VarChar).Value = textBox3.Text;
        da.InsertCommand.Parameters.Add("@EJob", SqlDbType.VarChar).Value = textBox4.Text;
        da.InsertCommand.Parameters.Add("@EBDate", SqlDbType.Date).Value = maskedTextBox1.Text;
        da.InsertCommand.Parameters.Add("@ESalary", SqlDbType.Int).Value = textBox5.Text;
    BTW you don't need any SqlDataAdapter or DataSet to execute an INSERT - it can be done with SqlConnection and SqlCommand only.
    Last edited by r.vector; 01-07-2012 at 03:07 AM.

  3. #3
    oh yeah right ,the insert command is for inserting stuff into Database , i choose selectcommand and this is wrong , oh that error made think of re installing sql server , but good that you was around thanks a lot .

+ Reply to Thread

Tags for this Thread


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts