ASP.Net ExecuteScalar Error: Must declare the scalar variable

Last Reply 10 days ago By dharmendr

Posted 10 days ago

I have an insert statement in the asp web form that before inserting the data into the database check it for duplicate data.

http://uupload.ir/files/6k3s_123123.png

this is my code that avoids inserting duplicate data: 

                string constr = ConfigurationManager.ConnectionStrings["KDUIS-v1ConnectionString"].ConnectionString;
                using (SqlConnection con = new SqlConnection(constr))
                {
                    using (SqlCommand cmd = new SqlCommand("SELECT * FROM EDU_Professor WHERE PersonId = @PersonId", con))
                    {
                        cmd.Parameters.AddWithValue("@PersonId", Convert.ToInt32(LblPersonId.Text));
                        using (SqlCommand cmd2 = new SqlCommand("SELECT * FROM EDU_SubjectStudy_Professor WHERE SubjectStudyId=@SubjectStudyId", con))
                        {
                            cmd.Parameters.AddWithValue("@SubjectStudyId",Convert.ToInt32(LblSubjectStudyId.Text));
                            con.Open();
                            string name = Convert.ToString(cmd.ExecuteScalar());
                            string name2 = Convert.ToString(cmd2.ExecuteScalar());
                            con.Close();
                            if (string.IsNullOrEmpty(name)&& string.IsNullOrEmpty(name2))
                            {
                                sqlDtSrcProfessor.Insert();
                                int ProfessorId = ProfId();
                                SqlDtSrcSSProf.Insert();
                                ScriptManager.RegisterStartupScript(this, this.GetType(), "CropImage", "alert('your data is inserted')", true);
                                TxtCode.Text = "";
                                txtday1.Text = "";
                                txtday2.Text = "";
                                TxtDescription.Text = "";
                                txtmonth1.Text = "";
                                txtmonth2.Text = "";
                                TxtProfessor.Text = "";
                                ListSubjectStudy.SelectedIndex = 0;
                            }
                            else
                            {
                                ScriptManager.RegisterStartupScript(this, this.GetType(), "CropImage", "alert('this field is duplicate')", true);
                            }
                        }
                       
                    }
                }

but when I want to run my code, I faced this error message.

and the type of SubjectStudyId is int.

You are viewing reply posted by: dharmendr 10 days ago.
Posted 10 days ago
dorsa says:
cmd.Parameters.AddWithValue("@SubjectStudyId",Convert.ToInt32(LblSubjectStudyId.Text));

 Change the above with the below code.

cmd2.Parameters.AddWithValue("@SubjectStudyId",Convert.ToInt32(LblSubjectStudyId.Text));