TD Lemon TD Lemon - 1 year ago 61
ASP.NET (C#) Question

Set custom error pages for ASP.GridView

I want to set a custom error page instead of the traditional one for my asp gridview connected to my database. For instance, when I try to delete an object that have some dependencies (foreign keys), I would like to display a userfriendly message for the user.

Thank you for your help.

Answer Source

If there is no place to catch the offending code then your best bet might be to use's custom error pages which will display a specific page whenever an unhandled exception occurs. To enable custom errors add the following section to the web.config file

<customErrors mode="On" defaultRedirect="~/Error/Error.aspx">

For more on custom errors take a look at:

In the custom error page add this code to the page load event to check what the last error was that occurred and display a friendlier message:

Exception lastError = HttpContext.Current.Server.GetLastError;
if (lastError is SqlClient.SqlException)  // Check that the last exception was a Sql Exception
    SqlClient.SqlException sqlex = (SqlClient.SqlException) lastError;
    switch (sqlex.Number) // Check what type of Sql error occurred
        case 124:  // FOREIGN KEY Constraint failed referential check upon DELETE of row in referenced table
            // Display appropriate error message on the page

For a more on the Sql error numbers go to