Click here to Skip to main content
15,890,438 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
SqlConnection con = new SqlConnection(@"Data Source=SATYA\SAT;Initial Catalog=record;Integrated Security=True");
                SqlDataAdapter da = new SqlDataAdapter("update  employee set empName=@Name,empContact=@Contact,EmpAddress=@address where empId=@ID", con);
                DataSet ds = new DataSet();
                da.Fill(ds);

                da.UpdateCommand.Parameters.Add("@ID", SqlDbType.Int).Value = emp.Id;
                da.UpdateCommand.Parameters.Add("@Name", SqlDbType.VarChar).Value = emp.Name.ToString();
                da.UpdateCommand.Parameters.Add("@Contact", SqlDbType.Int).Value = emp.Contact;
                da.UpdateCommand.Parameters.Add("@address", SqlDbType.Int).Value = emp.Address;


What I have tried:

It's give exception "
Must declare the scalar variable "@Name"
Posted
Updated 10-Mar-19 0:01am

1 solution

Look at your code.
You execute a command on a DataAdapter before you add the parameters.
And you try to fill a DataSet from an UPDATE command, which is weird and unlikely to work.
Use a command instead:
using (SqlConnection con = new SqlConnection(strConnect))
   {
   con.Open();
   using (SqlCommand cmd = new SqlCommand("UPDATE employee SET empName=@Name,empContact=@Contact,EmpAddress=@address WHERE empId=@ID", con);
      {
      cmd.Parameters.AddWithValue("@ID", emp.Id);
      cmd.Parameters.AddWithValue("@Name", emp.Name);
      cmd.Parameters.AddWithValue("@Contact", emp.Contact);
      cmd.Parameters.AddWithValue("@address", emp.Address);
      cmd.ExecuteNonQuery();
      }
   }
And don't hardcode connection strings! Always store them in a config file so that they only need to be changed in one place.
 
Share this answer
 
v2
Comments
satyanand mishra 10-Mar-19 6:23am    
I know this but I want to do this SqlAdapter through Update command I don't want to open my connection,can you explain it why it's give exception.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900