0

I need to make a button that delete rows from my dataset in C#, but I want datagridview selected rows to be deleted, how do I do that?

This is what was in the professor instructions, but unfortunatelly this isn't working for me.

            int lineNum = int.Parse(lineDelete.Text.ToString());
        SqlConnection sqlConn = new SqlConnection(ConnectionString);
        sqlConn.Open();
        string deleteSqlQuery = "select * from Clientes order by ID";
        SqlDataAdapter deleteDA = new SqlDataAdapter(deleteSqlQuery, sqlConn);
        DataSet deleteDS = new DataSet();
        deleteDA.Fill(deleteDS, "Clientes");
        deleteDS.Tables["Clientes"].Rows[lineNum].Delete();
        SqlCommandBuilder deleteCB = new SqlCommandBuilder(deleteDA);
        deleteDA.Update(deleteDS, "Clientes");
        deleteDA.Dispose();
        deleteDS.Dispose();
        deleteCB.Dispose();
        sqlConn.Close();
        CliCadForm_Load(null, null);
        CustTBoxID.Text = "";
        CustTBoxNome.Text = "";
        CustTBoxDDD.Text = "";
        CustTBoxTel.Text = "";
        CustTBoxEnde.Text = "";
        CustTBoxENum.Text = "";
        CustTBoxEComp.Text = "";
        CustTBoxEBai.Text = "";
        CustTBoxEUF.Text = "";
        CustTBoxECid.Text = "";
        CustTBoxECEP.Text = "";
        lineDelete.Text = "";

1 Answer 1

1

If I understand you, you can use something like this:

    private void DeleteSelectedRows()
    {
        using (SqlConnection con = new SqlConnection(ConnectionString))
        {
            con.Open();

            foreach(DataGridViewRow row in dataGridView.SelectedRows)
            {
                SqlCommand cmd = new SqlCommand("DELETE FROM Clientes WHERE ID="+row.Cells["ID"].Value, con);
                cmd.ExecuteNonQuery();
            }

            con.Close();
        }
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.