Jieha Lee

Jieha Lee

  • 1.6k
  • 186
  • 8.9k

How to get id from other table and insert in other table

Jan 28 2018 9:25 PM
How to I get id from 'Admin' table based on username(which is Session["admin"]) to insert in 'Message' table? I got the error as below when I use SqlDataReader to detect the id.
 
The error:
 
System.Data.SqlClient.SqlException: Must declare the scalar variable "@tel_no".
 
Here is the code that I use:
  1. protected void Button1_Click(object sender, EventArgs e)  
  2. {  
  3. SqlConnection con = new SqlConnection(@"Data Source=USER1-PC\SQLEXPRESS;Integrated Security=true;Database=STAFF_TEST");  
  4. con.Open();  
  5. SqlCommand getName = new SqlCommand("select id, customer_id from Admin", con);  
  6. SqlDataReader name = getName.ExecuteReader();  
  7. SqlCommand cmd = new SqlCommand("insert into Message(tel_no, message, timestamp, staff_id) values(@tel_no, @message, @timestamp, @staff_id)", con);  
  8. if (name.Read())  
  9. {  
  10. if (name["customer_id"].Equals(Session["admin"].ToString()))  
  11. {  
  12. cmd.Parameters.Add("@tel_no", SqlDbType.NVarChar).Value = Request.Form["offcell"];  
  13. cmd.Parameters.Add("@message", SqlDbType.NVarChar).Value = Request.Form["message"];  
  14. cmd.Parameters.Add("@timestamp", SqlDbType.DateTime).Value = DateTime.Now;  
  15. cmd.Parameters.Add("@staff_id", SqlDbType.NVarChar).Value = name["id"];  
  16. }  
  17. name.Close();  
  18. }  
  19. cmd.ExecuteNonQuery();  
  20. con.Close();  
  21. Response.Redirect("Default.aspx");  
  22. }  
Thanks.

Answers (2)