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

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.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s