Search code examples
c#sql-serverdatabaseooplayered

How to delete a list item with an query from a different form in c#?


I try to delete a list item from my list 'Ship' which is in my database. I use 2 classes to split apart my SQL queries (ShipDB.cs for my queries, Ship for my Ship properties). I want to use the delete button in my form to delete the selected row in my database. The button doesn't delete the row and no error mention has been given when clicking the delete button.

Here in the ShipDb.cs:

public void Delete()
        {
            using (System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection(connectionString))
            {

                connection.Open();
                Ship ship = new Ship();
                SqlCommand commandDelete = new SqlCommand("DELETE FROM Ship WHERE id = " + ship.Id, connection);
                commandDelete.ExecuteNonQuery();
            }
        }

Here in the Form1.cs:

private void Button3_Click(object sender, EventArgs e)
        {   

             using (System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection(connectionString))
                {


                if (dataGridViewShips.SelectedRows.Count == 1)
                {

                    Ship ship = (Ship)dataGridViewShips.SelectedRows[0].DataBoundItem;
                    db.Delete();
                    dataGridViewShips.DataSource = db.GetAll();

                }
            }

        }

I use the db.GetAll to update the database


Solution

  • As Sami said, you aren't telling it what needs deleted.

    public void Delete(Ship ship)
    {
        using (System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection(connectionString))
        {
            connection.Open();
            SqlCommand commandDelete = new SqlCommand("DELETE FROM Ship WHERE id = " + ship.Id, connection);
            commandDelete.ExecuteNonQuery();
         }
    }
    
    private void Button3_Click(object sender, EventArgs e)
    {   
        using (System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection(connectionString))
        {
            if (dataGridViewShips.SelectedRows.Count == 1)
            {
                Ship ship = (Ship)dataGridViewShips.SelectedRows[0].DataBoundItem;
                db.Delete(ship);
                dataGridViewShips.DataSource = db.GetAll();
            }
        }
    }