views:

427

answers:

2

I want to be able to wrap a gridview row delete in a try catch and display a nice error message on the screen or try to stop the delete from happening in certain circumstances.

At the moment, I am getting foreign key violations in the database. So I either want to stop the delete from happening if there are child records or catch the foreign key exception and display a nice error message to the screen.

Can anyone tell me how to do this?

+3  A: 

You can use GridView Row Deleting Event

Here is a sample code for that :

void CustomersGridView_RowDeleting
        (Object sender, GridViewDeleteEventArgs e)
    {
        TableCell cell = CustomersGridView.Rows[e.RowIndex].Cells[2];
        if (cell.Text == "Beaver")
        {
            e.Cancel = true;
            Message.Text = "You cannot delete customer Beaver.";
        }
        else
        {
            Message.Text = "";
        }
    }
Braveyard
+1 for "custom beaver"
recursive
Another +1 for the same beaver!
o.k.w
When does the row deleting fire? Before or after the associated data source delete? I tried the above but it doesn't seem to be be called.
GordyII
@Gordyll : There is actually two different events handler to handle the row deleting and row deleted. Row deleting will be fired when row is being deleted so you have a chance to cancel the deletion process or change same during that process but row_deleted is fired after the selected row is completely deleted. You can find more information Here : http://is.gd/4ipXz go ahead and have a look, you like it ;)
Braveyard
A: 

Using the datasource Deleting event might be cleaner as one does not depend on the GUI elements and their possible repositioning that might break the code.

Tarik