Sunday, July 19, 2009

How to determine if object from database is null (C#)

When you are getting data out of your database you may need to do some type checking. This is important if the field allows null.

For example, if you have an nvarchar(#) that allows Null, you'll want to check if you are getting a Null string so that you can safely set it to "" (empty string) or whatever value you want. This prevents exceptions from being thrown.

Code (ADO.NET C#):

Using one line:
string columnName = reader["columnName"].GetType() == Type.GetType("System.DBNull") ? "" : reader["columnName"].ToString();

Using if, then:
if(reader["columnName"].GetType() == Type.GetType("System.DBNull"))
columnNameVariable = ""; //or whatever value you want to set it to
else
columnNameVariable = reader["columnName"].ToString();

No comments:

Post a Comment

There was an error in this gadget