the code below is my delete button, but the problem is i dont know how to make i
ID: 3776005 • 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 'New York' and i dont want that i just want it to delete the specific one i want 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
Asnwer :-
step 1. First we show details in gried view .
private void Incidents_Load(object sender, EventArgs e)
{
string grd = "select * from Incidents ";
SqlCommand cmd = new SqlCommand(grd, con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
dataGridView1.DataSource = dt;
con.Close();
}
step 2 . we can write delete code using grid view .
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
else if (e.ColumnIndex == 0)
{
string s = "delete from Incidents where Id ='" + dataGridView1.Rows[e.RowIndex].Cells["Id"].Value.ToString() + "'";
SqlCommand cmd = new SqlCommand(s, con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
dataGridView1.Rows.RemoveAt(e.RowIndex);
MessageBox.Show("delete data...................!");
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.