I have a windows form which has a DataGrid control (Not DataGridView) on it.
The DataGrid control is bound to a DataTable. Everytime the user presses the delete button on one of the rows on the grid, I want to check a condition and stop the row from being deleted if the condition is false.
I have subscribed to the RowDeleting event of the DataTable, but i cant find a way to cancel to the delete operation performed by the user. How can i achieve this ?
Although this thread is 2 years old, I add the answer just in case someone stumbles across.
For each row in a DataTable, there is method "RejectChanges()", which you can use to undo a delete.
I did as follows:
a) To the DataTable, add a "RowDeleted" Handler:
dt.RowDeleted += new DataRowChangeEventHandler(dt_RowDeleted);
b) In the handler, call the functon "RejectChanges()" as follows:
void dt_RowDeleted(object sender, DataRowChangeEventArgs e)
{
if ( ... Add your condition here ... )
e.Row.RejectChanges();
}
Much easier than the above solutions.
In the UserDeletingRow event just call e.Cancel = true;
DialogResult dlgRes = MessageBox.Show("Are you sure that you want to delete this Factor?", "DELETE ITEM?", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (dlgRes == DialogResult.Yes)
{
//WBSDA.Delete(dgvR.Cells["WBSID"].Value.ToInt());
tslMessage.Text = "Item Deleted";
}
else
e.Cancel = true;
Rubens
Thanks for you response. I had already looked up that thread, but couldnt find a useful solution.
I just slightly modified my project, I now have a delete button instead of deleting directly from the datagrid itself.
I changed my DataTable to disallow any deletes
dataTable.DefualtView.AllowDelete = false
and in the delete button click handler, i wrote the following code:
(datagridStandardRates.DataSource as DataTable).Rows[datagridStandardRates.CurrentRowIndex].Delete();
This gives me complete control over when I want to delete a row.
Thanks once again for your help.
Raghu
My first thought was to suggest "e.Cancel = true;" but that property isn't available.
Googling a bit I came across How do I cancel a row delete in a DataSet ; please, take a look.
HTH
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.