簡體   English   中英

使用 C# 刪除 datagridview 和數據庫中的行

[英]Delete row in datagridview and database with C#

我制作了一個數據庫和一個帶有 datagridview 的程序來顯示數據庫內容。 現在我想制作一個按鈕讓用戶刪除一行並將其也刪除到數據庫中。

我嘗試了在 Stackoverflow 中找到的以下解決方案: How to delete row datagrid..

但我收到以下錯誤: 在此處輸入圖片說明

該錯誤告訴我未找到SqlConnection類型。

我在這里鏈接的整個代碼: Pastebin

        private void button5_Click(object sender, EventArgs e)
    {
        if (dataGridView1.SelectedRows.Count == 0)
            return;

        string sql = "DELETE FROM ticket.support WHERE ID = @rowID";

        using (SqlConnection myConnection = new SqlConnection("...."))
        using (SqlCommand deleteRecord = new SqlCommand(sql, myConnection))
        {
            myConnection.Open();

            int selectedIndex = dataGridView1.SelectedRows[0].Index;
            int rowID = Convert.ToInt32(dataGridView1[0, selectedIndex].Value);

            deleteRecord.Parameters.Add("@rowID", SqlDbType.Int).Value = rowID;
            deleteRecord.ExecuteNonQuery();

            dataGridView1.Rows.RemoveAt(selectedIndex);
        }

您需要添加對 System.Data.SqlClient 的引用。

在 Visual Studio 中,您可以展開項目,右鍵單擊“引用”並單擊“添加引用”,導航到實際引用並將其添加到項目中。 請參閱: https : //docs.microsoft.com/en-us/visualstudio/ide/managing-references-in-a-project?view=vs-2019

另請參閱: https : //docs.microsoft.com/en-us/visualstudio/ide/how-to-add-or-remove-references-by-using-the-reference-manager?view=vs-2019

如果缺少引用,則可以通過NuGet 包管理器下載它。

暫無
暫無

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

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