The Self-Taught Programmer

Recipes from real-world experience with

Posts Tagged ‘exception

Elmah Signaling – How To Log Exceptions with Elmah but Continue Processing

leave a comment »

Elmah is an excellent tool for web programmers. It is an extremely easy to install exception handler that logs application exceptions and sends the user to an “oops” page. It can also send an email to the developer or webmaster.

But what if you want to log an error but NOT send the user to an “oops” page. This can be especially useful in debugging code that already handles exceptions so that the user doesn’t see them.

Here is how it works:

Add a reference to Elmah to the page:

using Elmah;

Then, in your try/catch block, use this code:

    //some code}
catch (Exception ex)
    // handle your exception here
    ErrorSignal.FromCurrentContext().Raise(ex); //ELMAH Signaling  (logs error but processing continues)
    return false;  //assuming the method returns a boolean value.

Written by Jim McMullen

May 5, 2011 at 3:18 pm

Posted in How-To

Tagged with , ,

How To Avoid Null Reference Exceptions in an ASPX File When Dynamically Populating a GridView or ListView Control

leave a comment »

The situation:

You have a GridView control with a TemplateField in your ASPX page that is dynamically populated from a database. You of course use an Eval() statement to dynamically populate the TemplateField, but the db field is nullable (and in fact contains a null value), and when you run the page, you get an NullReferenceException because you are trying to bind to a null value.

This is your basic (simplified) code that is causing the error (because “Cost” is null):

<asp:GridView id="MyGridView"
		<asp:TemplateField HeaderText="Cost">
				<%# Eval("Cost") %>

Here is the fix: Add this method to your codebehind:

	protected string CheckNull(object objGrid)
		if ( object.ReferenceEquals(objGrid, DBNull.Value) )
			return "not available";
		else if ( objGrid == null )
			return "not available";
			return objGrid.ToString();

You can change “not available” to any value you wish.

Then your template field should be changed to:

<%# CheckNull(Eval("Cost")) %>

And that should fix the issue.

Written by Jim McMullen

May 3, 2011 at 2:40 pm