Reputation: 23
When I enter iD value it shows:
Must declare the scalar variable "@studentID".
****
This is my class code
public void Add()
{
SqlConnection sqlCon = new SqlConnection("server = (LocalDB)\\MSSQLLocalDB ; Database = Online Medical Store; integrated security = true");
sqlCon.Open();
SqlCommand cmd = new SqlCommand("select StudentID, LastName, FirstName, FatherName, Address, City, Contact, EmailAddress from tblStudents where " +
"StudentID=@studentID and LastName=@lastName and FirstName=@firstName and FatherName=@fatherName and Address=@address and City=@city and Contact=@contact" +
" and EmailAddress=@emailAddress ", sqlCon);
cmd.Parameters.AddWithValue("@studentID", studentId);
cmd.Parameters.AddWithValue("@lastName", LastName);
cmd.Parameters.AddWithValue("@firstName", FirstName);
cmd.Parameters.AddWithValue("@fatherName", FatherName);
cmd.Parameters.AddWithValue("@address", Address);
cmd.Parameters.AddWithValue("@city", City);
cmd.Parameters.AddWithValue("@contact", Contact);
cmd.Parameters.AddWithValue("@emailAddress", EmailAddress);
SqlDataReader Dr = cmd.ExecuteReader();
if (Dr.HasRows == true)
{
throw new Exception("This Record is already Exists");
}
else
{
SqlConnection con = new SqlConnection("server = (LocalDB)\\MSSQLLocalDB ; Database = Online Medical Store; integrated security = true");
con.Open();
SqlCommand sqlcmd = new SqlCommand
("insert into tblStudents (StudentID,LastName,FirstName," +
"FatherName,Address, City, Contact, EmailAddress) " +
"values (@studentID,@lastName,@firstName,@fatherName,@address," +
"@city, @contact,@emailAddress)", con);
cmd.Parameters.AddWithValue("@studentID", studentId);
cmd.Parameters.AddWithValue("@lastName", LastName);
cmd.Parameters.AddWithValue("@firstName", FirstName);
cmd.Parameters.AddWithValue("@fatherName", FatherName);
cmd.Parameters.AddWithValue("@address", Address);
cmd.Parameters.AddWithValue("@city", City);
cmd.Parameters.AddWithValue("@contact", Contact);
cmd.Parameters.AddWithValue("@emailAddress", EmailAddress);
sqlcmd.ExecuteNonQuery();
}
sqlCon.Close();
}
Upvotes: 1
Views: 907
Reputation: 89256
You're adding the parameters to the wrong SqlCommand. This
cmd.Parameters.AddWithValue("@studentID", studentId);
should be
sqlcmd.Parameters.AddWithValue("@studentID", studentId);
Upvotes: 2