Click here to Skip to main content
15,893,381 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
protected void Add_Click(object sender, EventArgs e)
      {


          string constr = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
          SqlConnection con = new SqlConnection(constr);
          //SqlCommand cmd = new SqlCommand("insert into Student values('" + RegNo.Text + "','" + Name.Text + "','" + Address.Text + "')");
          SqlCommand cmd = new SqlCommand("insert into Student(@RegNo,@Name,@Address,@CreatedTime) values(@RegNo,@Name,@Address,Getdate())");

          cmd.Connection = con;
          con.Open();

          cmd.ExecuteNonQuery();
          con.Close();

      }


What I have tried:

here am try to insert records . i have 3 textboxes namely RegNo,Name,Address and in my table I have $ columns RegNo,Name,Address,CreatedTime. in my code the following error encountered .
Must declare the scalar variable @RegNo .
what to do.
Posted
Updated 1-Feb-18 20:56pm
Comments
Richard Deeming 2-Feb-18 10:25am    
Further to solution 1, you also have a syntax error in your SQL statement. It should be:
insert into Student(RegNo,Name,Address,CreatedTime) values(@RegNo,@Name,@Address,Getdate())
The first list in brackets is the list of columns you're inserting to. By prefixing them with @, you're trying to use the parameter values instead.

1 solution

When you create a parameterised query - and that is exactly the right way to do SQL operations - you have to also create a Parameter which contains teh value you wish to pass to SQL. It's a bit like calling a method in C#. You define it
C#
public int DoInsert(int regNo, string name, string address, DateTime insertDate)
   {
   ...
   }
But when you call it, you must provide the values:
C#
int rowsAffected = DoInsert(666, "Mike Smith", "2 Main Street, Kentucky", DateTime.Now);
If you miss out any parameters, you get a compiler error.
SQL is the same.
Add a line for each parameter:
C#
cmd.Parameters.AddWithValue("@NameOfParameterInSQLCommand", valueIWantInTheColumn);
And it'll start to work.
 
Share this answer
 
Comments
Ehsan Sajjad 3-Feb-18 13:42pm    
5ed

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