HelpIT2021-01-10 01:12:41
C++ / C#
HelpIT, 2021-01-10 01:12:41

After launch, this notification is issued: System.InvalidOperationException:?

After clicking on the insert button, the following appears:

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();
                dal.connectionOpen();               // Connection Open есть в другом файле Data Access Layer
                if (getStudentID(this.studentNo) == -1)
                    sqlCommand.Connection = sqlConnection;
                    return "new student inserted";
                    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 = " ";


Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question