0

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

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Robin R
  • 21
  • 5
  • 3
    You’re not providing the delete method any information of what to delete. You’re just creating a new object which probably has 0 as an id and that’s deleted – Sami Kuhmonen Jun 30 '19 at 18:38
  • 2
    [SQL Injection alert](http://msdn.microsoft.com/en-us/library/ms161953%28v=sql.105%29.aspx) - you should **not** concatenate together your SQL statements - use **parametrized queries** instead to avoid SQL injection - check out [Little Bobby Tables](http://bobby-tables.com/) – marc_s Jun 30 '19 at 19:35

1 Answers1

1

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();
        }
    }
}
Nate H
  • 26
  • 3