How to implement soft deletion in DataGridView

1.1k Views Asked by At

I have a DataGridView bound to a object data source. The object has a property "IsDeleted". When the user presses the delete key, or clicks the delete button, or deletes a row in some other way, i want to set the "IsDeleted" flag instead of removing the row. (I then want the datagridview to update).

What is the single point of contact i need to achieve this behaviour?

I don't want to try to handle all the user paths seperately.

1

There are 1 best solutions below

4
On

You can handle the event UserDeletingRow to Cancel it manually and perform your own deletion like this:

private void dataGridView1_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e){
   e.Cancel = true;//Cancel the actual deletion of row
   //You can just hide the row instead
   e.Row.Visible = false;
   //Then set the IsDeleted of the underlying data bound item to true
   ((YourObject)e.Row.DataBoundItem).IsDeleted = true;
}

You just said that your object has a property called IsDeleted, so I suppose it's called YourObject, you have to cast the DataBoundItem to that type so that you can access the IsDeleted property and set it to true. That's all.