Click here to Skip to main content
15,935,248 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more: , +
I have a application where I need to use the buttons in the datagridview to delete a selected row. I know how to do that part but i need it to also update the database. That's what I'm struggling with.

What I have tried:

So this what I have it does delete the selected row when application is running but once the application is closed and ran again the deleted row is back.
C#
private void RecordsdataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)

if (RecordsdataGridView.Columns[e.ColumnIndex].Name == "Delete")
{
DialogResult result = MessageBox.Show("Are you sure you want to delete this patient report?", "Conformation", MessageBoxButtons.YesNo);

                if (result == DialogResult.Yes)

                {
                int rowIndex = RecordsdataGridView.CurrentCell.RowIndex;

               RecordsdataGridView.Rows.RemoveAt(rowIndex);
}

         else if (result == DialogResult.No)

                {
                    Application.Exit();
                }
}
Posted
Updated 28-Apr-20 15:30pm
v2

1 solution

One way of doing this, is, before this line
RecordsdataGridView.Rows.RemoveAt(rowIndex);

read the required (index) data from the selected DataGrid Row, and use that to run a 'delete from table where id = index-from-datarow' sort of thing - making sure you do the SQL properly, ie, no SQL injection, use a parameterized SQL statement.

If the DataGrid Row doesn't have an index or something to form a unique delete statement, then I suggest you change your original query to obtain it, but make the DataGrid column hidden so it doesnt display

Probably a better way of achieving the update/delete of an 'underlying' database table from a DataGridView is to 'bind' the DataGridView to the data-source (db table) - here's a link that may help illustrate this Database Updates From DatagridView[^]
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900