Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

the code below is my delete button, but the problem is i dont know how to make i

ID: 3776581 • Letter: T

Question

the code below is my delete button, but the problem is i dont know how to make it specific for the exact row i want to delete, because when i run it works but it would delete all rows that has the word 'New York' in it and i dont want that i just want it to delete the specific one i clicked on from the database. How to modify it ?
string connetionString = null;
OleDbConnection connection;
OleDbDataAdapter oledbAdapter = new OleDbDataAdapter();
string sql = null;
connetionString = @"Provider = Microsoft.ACE.OLEDB.12.0; Data Source=C:UserssereneDesktopsamb - CopysambPublic.accdb; Persist Security Info = False;";
connection = new OleDbConnection(connetionString);
sql = "delete from Incidents where Location = 'New York'";
try
{
connection.Open();
oledbAdapter.DeleteCommand = connection.CreateCommand();
oledbAdapter.DeleteCommand.CommandText = sql;
oledbAdapter.DeleteCommand.ExecuteNonQuery();
MessageBox.Show("Row(s) Deleted !! ");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
Note: I have 4 tables in the databaseans their name is (Incident Report No,Occurrence Time,Gategory of Incident,Location)

Explanation / Answer

sql = "delete from Incidents where Location = 'New York'"; it will delete all the records that have location =New York

If you want to delete the specific row then you can modify your code as

string connetionString = null;
string sql = null;
connetionString = @"Provider = Microsoft.ACE.OLEDB.12.0; Data Source=C:UserssereneDesktopsamb - CopysambPublic.accdb; Persist Security Info = False;";
foreach(DataGridViewRow row in DataGridView1.SelectedRows)
{
int rowIdToDelete = row.Cells[0].Value;
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
string query = "DELETE FROM [Incidents ] WHERE Incident_Report_No = " + rowIdToDelete;
                       //Incident_Report_No is the name of column that is at 0 position in gridview

conn.Open();

using (OleDbCommand cmd = new OleDbCommand(query, conn))
{
using (OleDbDataAdapter adapter = new OleDbDataAdapter(query, conn))
{
DataTable ds = new DataTable();
adapter.Update(ds);
dataGridView.DataSource = ds;
cmd.ExecuteNonQuery();
}
}
}
}

}