TD Lemon TD Lemon - 3 months ago 13
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

If there is no place to catch the offending code then your best bet might be to use asp.net'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">
</customErrors>

For more on custom errors take a look at: http://www.asp.net/web-forms/tutorials/deployment/deploying-web-site-projects/displaying-a-custom-error-page-cs

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
            break;
    }
}

For a more on the Sql error numbers go to http://www.scribd.com/doc/7679522/SQL-Server-Error-Codes

Comments