-3

I have an "addstock" form and a "viewstocks" form in two different forms.

When I add the stock_no and details in the addstock form and come back press the "refresh button " which is in the viewstock form; the new record will appear in the viewstock form.

The viewstock form has the delete button also.

When I select the row and press delete, I get this error

Must declare the scalar variable "@Stockno"

I need to call it. please help,

private void bunifuFlatButton3_Click(object sender, EventArgs e)
{
    try 
    {
        conn.Close();
        conn.Open();

        String DeleteQuery = "delete from Stocks_Item where Stock_code = (@Stockno)";

        SqlDataAdapter execute = new SqlDataAdapter(DeleteQuery, conn);
        execute.SelectCommand.ExecuteNonQuery();

        MessageBox.Show("You've deleted successfully!", "Successful Message", MessageBoxButtons.OK, MessageBoxIcon.Information);

        conn.Close();
        cmd.ExecuteNonQuery();

        SqlDataAdapter data = new SqlDataAdapter("Select * from Stocks_Item", conn);
        DataTable dt = new DataTable();
        data.Fill(dt);

        dataGridView1.DataSource = dt;
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "Error Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • 5
    You have not even added the actual value you want to compare against in the delete. I have the impression you have written code you don‘t entirely understand. – Sefe Dec 17 '17 at 09:23

1 Answers1

1

You should NOT use a SqlDataAdapter when you want to delete something - use a stand-alone SqlCommand - like this:

private void bunifuFlatButton3_Click(object sender, EventArgs e)
{
    try 
    {
        conn.Close();

        string DeleteQuery = "delete from Stocks_Item where Stock_code = @Stockno";

        SqlCommand cmdDelete = new SqlCommand(DeleteQuery, conn);
        -- add the parameter!
        cmdDelete.Parameters.Add("@stockno", SqlDbType.Int).Value = (provide the value for `@stockno` here!);

        // open connection, execute command, close connection
        conn.Open();
        cmdDelete.ExecuteNonQuery();
        conn.Close();

        MessageBox.Show("You've deleted successfully!", "Successful Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
        .....
    }
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459