簡體   English   中英

無法從表單中刪除記錄

[英]Cant delete a record from the form

我有兩種形式。 一種是輸入庫存,另一種是在網格視圖中查看庫存。 所以現在當我需要刪除一條記錄時,我曾經從網格視圖中選擇記錄,然后雙擊該單元格,那么“庫存條目”將與所有現有記錄一起打開。 然后,當我單擊“刪除按鈕”時,它表示已成功刪除,但在網格視圖或數據庫中未進行任何更改。數據仍然存在。 請幫我謝謝。

鏈接到我的sql: https : //drive.google.com/open? id = 1D5EpLZZ- 2yVlOphaSBxOSC2vVLGabZ7W

我的ID設置為自動遞增,並且索引類型設置為我的股票為“唯一”

private void bunifuFlatButton3_Click(object sender, EventArgs e)
{
 try
    {
        conn.Close();
        conn.Open();
        String DeleteQuery = "Delete from Stock_Jewelry where ID ='" + txt_ID + "';";
        SqlDataAdapter execute = new SqlDataAdapter(DeleteQuery, conn);
        execute.SelectCommand.ExecuteNonQuery();
        MessageBox.Show("You've deleted successfully!", "Successful Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
        conn.Close();
        this.Close();
    }

    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "Error Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
    conn.Close();
}

請嘗試執行此操作,因為Id類型為int且txt_ID必須轉換為int;

String DeleteQuery = "Delete from Stock_Jewelry where ID =" + txt_ID;

正如人們提到的那樣,您的代碼注入不安全,因此最好使用SqlParameter解決問題:

通過SqlDataAdapter嘗試一下:

   try
   {
        SqlConnection connection = new SqlConnection(conn);
        SqlDataAdapter adapter = new SqlDataAdapter();
        connection.Open();
        adapter.DeleteCommand = connection.CreateCommand();
        adapter.DeleteCommand.CommandText = "Delete from Stock_Jewelry where ID =@id";
        adapter.DeleteCommand.Parameters.AddWithValue("@id", txt_ID.Trim());
        adapter.DeleteCommand.ExecuteNonQuery();
        MessageBox.Show("Row(s) deleted !! ");
    }
    catch (Exception ex)
    {
            MessageBox.Show(ex.ToString());
    }

或最簡單的方式:

SqlConnection con = new SqlConnection(conn);
SqlCommand cmd = new SqlCommand("Delete from Stock_Jewelry where ID =@id", con);
con.Open();
cmd.Parameters.AddWithValue("@id", txt_ID.Trim());
cmd.ExecuteNonQuery();

注意:

當Query在DB中運行時沒有問題,這意味着您的代碼沒有問題,否則讓我們知道另一端是什么異常,則txt_ID存在問題,例如其中有空格,或者DB中不存在輸入的ID 。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM