This error arises when i use parametrised query (Must declare the scalar variable @"regNo")

61 Views Asked by At

Execute.nonquery is giving the error of must declare the scalar variable.. please tell me solution

 private void btndelete_Click(object sender, EventArgs e)
    {
        using (SqlConnection con = new SqlConnection(cs))
          {
         con.Open();
         string query = "delete stu_data where Reg_no=@regNo";
         SqlDataAdapter sda = new SqlDataAdapter(query,con);
         sda.SelectCommand.Parameters.AddWithValue("@regNo", textBox1.Text.ToString());
         sda.DeleteCommand = con.CreateCommand();
         sda.DeleteCommand.CommandText = query;
         sda.DeleteCommand.ExecuteNonQuery();
          }

  }
    }
1

There are 1 best solutions below

0
asapProg666 On

Here you have a nice delete example:

try
{
    using (var sc = new SqlConnection(ConnectionString))
    using (var cmd = sc.CreateCommand())
    {
        sc.Open();
        cmd.CommandText = "DELETE FROM excludes WHERE word = @word";
        cmd.Parameters.AddWithValue("@word", word);  
        cmd.ExecuteNonQuery();
    }
}
catch (Exception e)
{
    Box.Text = "SQL error" + e;
}

Or if you are using SqlDataAdapter:

command = new SqlCommand("DELETE FROM Customers WHERE CustomerID = @CustomerID", connection);

// Add the parameters for the DeleteCommand.
parameter = command.Parameters.Add("@CustomerID", SqlDbType.NChar, 5, "CustomerID");
parameter.SourceVersion = DataRowVersion.Original;

adapter.DeleteCommand = command;
adapter.DeleteCommand.ExecuteNonQuery();