2

i am trying to update my data from webservice to my database. But once i click invoke in the web service page , and run to this command:"command1.Connection.Open();" i will receive this error message :Object reference not set to an instance of an object.

this is my code:

  [WebMethod]
        public void UpdateParticulars(string Name, string CLass, string NRIC, float AmountSpent)
        {
            using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ncpConnectionString2"].ConnectionString))
            {
                SqlCommand command1 = new SqlCommand("UPDATE Student set Name=@Name, Class=@CLass,StallNo=@StallNo,AmountSpent=@AmountSpent WHERE NRIC = '" + NRIC + "'");

                command1.Parameters.AddWithValue("@Name", Name);
                command1.Parameters.AddWithValue("@Class", CLass);
                command1.Parameters.AddWithValue("@NRIC", NRIC);
                command1.Parameters.AddWithValue("@AmountSpent", AmountSpent);

                command1.Connection.Open();
                command1.ExecuteNonQuery();
            }
        }
3
  • 2
    Change this command1.Connection.Open(); to conn.Open(); Commented Jul 26, 2013 at 7:05
  • having this error : System.Data.SqlClient.SqlException: Must declare the scalar variable "@StallNo". Commented Jul 26, 2013 at 7:14
  • you have added that paramater. Add this command1.Parameters.AddWithValue("@StallNo", ""); Commented Jul 26, 2013 at 7:24

3 Answers 3

8

Pass your SqlConnection as argument to SqlCommand constructor.

SqlCommand command1 = new SqlCommand(query, conn);

Also change your query to be fully parametrized (and you are missing @StallNo parameter):

"UPDATE Student set Name=@Name, Class=@CLass,StallNo=@StallNo,AmountSpent=@AmountSpent WHERE NRIC = @NRIC"

command1.Parameters.AddWithValue("@Name", Name);
command1.Parameters.AddWithValue("@Class", CLass);
command1.Parameters.AddWithValue("@NRIC", NRIC);
command1.Parameters.AddWithValue("@AmountSpent", AmountSpent);
command1.Parameters.AddWithValue("@StallNo", ""); //missing parameter
Sign up to request clarification or add additional context in comments.

2 Comments

i got this errror: System.Data.SqlClient.SqlException: Must declare the scalar variable "@StallNo".
I pointed that out in my answer (and you are missing @StallNo parameter): must add this command1.Parameters.AddWithValue("@StallNo", ""); //missing parameter with proper value.
0

use command1.Connection=conn; conn.Open();

Before executing ExecuteNonQuery()

Comments

0

Just add this line

conn.open();

instead of

command1.Connection.Open();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.