Home > Software engineering >  how to solve the problem(@id needs to be declared) in sqladapter.InsertCommand c# ado.net
how to solve the problem(@id needs to be declared) in sqladapter.InsertCommand c# ado.net

Time:02-14

I keep getting this error

System.Data.SqlClient.SqlException: La variable scalaire "@id" doit être déclarée.

on the adapter's insert command , even if my value is declared in the parameters what should i do ? here is the code

private void BT_Add_Click(object sender, EventArgs e)
        {
            adapter.SelectCommand.Parameters.AddWithValue("@id", txtID.Text);
            adapter.SelectCommand.Parameters.AddWithValue("@name", txtName.Text);
            adapter.SelectCommand.Parameters.AddWithValue("@lastname", txtLastName.Text);
            adapter.SelectCommand.Parameters.AddWithValue("@adress", txtAdress.Text);
            adapter.SelectCommand.Parameters.AddWithValue("@email", txtEmail.Text);
            connection.Open();
            adapter.InsertCommand = new SqlCommand("insert into client values(@id,@name,@lastname,@adress,@email)", connection);
            adapter.InsertCommand.ExecuteNonQuery();
            MessageBox.Show("Row inserted !! ");}

it's better to use an SqlCommand thanks

 private void parameters()
        {
            command.Parameters.Clear();
            command.Parameters.AddWithValue("@id", txtID.Text);
            command.Parameters.AddWithValue("@name", txtName.Text);
            command.Parameters.AddWithValue("@lastname", txtLastName.Text);
            command.Parameters.AddWithValue("@adress", txtAdress.Text);
            command.Parameters.AddWithValue("@email", txtEmail.Text);
        }
        private void BT_Add_Click(object sender, EventArgs e)
        {
            parameters();
            command.CommandText = "insert into client values(@id,@name,@lastname,@adress,@email)";
            command.ExecuteNonQuery();
            MessageBox.Show("Row inserted !! ");}

CodePudding user response:

You've added parameters to the SelectCommand; this does not automatically add them to the InsertCommand. The two commands are different things

You don't need an adapter here; just make a new SqlCommand, set the SQL, add the parameters to it and execute it

  • Related