简体   繁体   中英

Delete row in datagridview and database with C#

I made a database and a program with a datagridview to show the database content. Now I want to make a button to let users delete a row and delete it also in the database.

I tried the following solution which I found in Stackoverflow: How to delete row datagrid..

But I get following Error: 在此处输入图片说明

The error tells me that the type SqlConnection was not found.

My whole code I've linked here: 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);
        }

You need to add a reference to System.Data.SqlClient.

In Visual Studio you can expand a project, right-click on References and click on Add Reference, navigate to the actual reference and add it to the project. See: https://docs.microsoft.com/en-us/visualstudio/ide/managing-references-in-a-project?view=vs-2019

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

If a reference is missing, then you can download it via the NuGet Package Manager .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM