@HelpIT

После запуска выдается вот это уведомление: System.InvalidOperationException:?

После нажатия на insert button появляется:
System.InvalidOperationException: Для ExecuteNonQuery нужно открытое и доступное подключение Connection. Подключение закрыто. в System.Data.SqlClient.SqlCommand.ValidateCommand(String method, Boolean async) в System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry) в System.Data.SqlClient.SqlCommand.ExecuteNonQuery() в WebApplication1.Student.insertNewStudent() в C:\Users\acer-pc\source\repos\WebApplication1\Student.cs:строка 95 


public string insertNewStudent()
        {
            string query = "inset into Students values(@fName, @lName, @studentNo);";
            SqlCommand sqlCommand = new SqlCommand();
            SqlConnection sqlConnection = new SqlConnection();
            sqlCommand.CommandText = query;
            sqlCommand.Parameters.AddWithValue("@fName", this.firstName);
            sqlCommand.Parameters.AddWithValue("@lName", this.lastName);
            sqlCommand.Parameters.AddWithValue("@studentNo", this.studentNo);
            DataAccessLayer dal = new DataAccessLayer();
            try
            {
                dal.connectionOpen();               // Connection Open есть в другом файле Data Access Layer
                if (getStudentID(this.studentNo) == -1)
                {
                    
                    sqlCommand.Connection = sqlConnection;
                    sqlCommand.ExecuteNonQuery();
                    dal.connectionClose();
                    return "new student inserted";
                }
                else
                {
                    dal.connectionClose();
                    return "the student with the " + this.studentNo.ToString() + " is already in the database";
                }

            }
            catch (Exception ex)
            {
                return ex.ToString();
            }
        }

// и button для insert 
 protected void btnInsert_Click(object sender, EventArgs e)
        {
            
            Student student = new Student();
            string fName = txtBoxfName.Text;
            string lName = txtBoxlName.Text;
            int studentNo=Convert.ToInt32(txtBoxStudentNo2.Text);
            
            labInsertInfo.Text = student.insertNewStudent();
            student.setStudentProperties(fName, lName, studentNo);

            txtBoxfName.Text = " ";
            txtBoxlName.Text = " ";
            txtBoxStudentNo2.Text = " ";


        }
  • Вопрос задан
  • 1110 просмотров
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы