Click here to Skip to main content
15,902,832 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
public int Insert(Student s)
       {
           con.Open();
           cmd = new SqlCommand("Insert into Students (stdid, studname) values" + "(@stdid, @studname)", con);
           SqlParameter[] prm = new SqlParameter[2];
           prm[0] = new SqlParameter("@stdid",SqlDbType.Int);
           prm[1] = new SqlParameter("@studname", SqlDbType.VarChar, 50);
           prm[0].Value = s.studentid;
           prm[1].Value = s.studentname;
           cmd.CommandType = CommandType.Text;
           return cmd.ExecuteNonQuery();

       }


I am getting error like this.

Must declare the scalar variable "@stdid".
Posted

You don't add the parameters to the command, so add to your code:
C#
...
cmd.Parameters.Add(prm[0]);
cmd.Parameters.Add(prm[1]);
...
 
Share this answer
 
Comments
Monjurul Habib 24-Dec-11 3:24am    
5!
Wendelius 24-Dec-11 3:28am    
Thanks :)
You declare a new parameters block, but you don't use it!
Try:
C#
public int Insert(Student s)
{
    con.Open();
    cmd = new SqlCommand("Insert into Students (stdid, studname) values" + "(@stdid, @studname)", con);
    // SqlParameter[] prm = new SqlParameter[2];
    // prm[0] = new SqlParameter("@stdid",SqlDbType.Int);
    // prm[1] = new SqlParameter("@studname", SqlDbType.VarChar, 50);
    // prm[0].Value = s.studentid;
    // prm[1].Value = s.studentname;
    cmd.Parameters.AddWithValue("@stdid", s.studentid);
    cmd.Parameters.AddWithValue("@studname", s.studentname);
    cmd.CommandType = CommandType.Text;
    return cmd.ExecuteNonQuery();
 }

Note that Parameters.Add (which you are effectively using) is depreciated in favour of AddWithValue, as shown above.
 
Share this answer
 
Comments
Monjurul Habib 24-Dec-11 3:25am    
5!
Wendelius 24-Dec-11 3:29am    
5'd
 
Share this answer
 
Comments
Wendelius 24-Dec-11 3:28am    
Good examples, 5
Monjurul Habib 24-Dec-11 3:30am    
thank you

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