Remove nulls from a DataTable

Dec 21, 2006

The individual cells in a DataTable can have a null value in the form of System.DbNull.Value. If the DataTable is created by querying a database through ADO.NET, you can write the SQL statement in a way eliminates nulls. It could look like this “SELECT isnull(name, 'n/a') AS name FROM products”.

However, there can be scenarios where you don’t have the chance to manipulate the DataTable before you use it. Such a scenario have I recently been involved in and the problem was that the data retrieved from a database could contain nulls in any of the integer type columns. If I then bind the DataTable to a GridView in ASP.NET, I had to do a lot of workarounds to calculate footers and other values based on those columns.

Instead of doing the workarounds in a lot of different places in the code, I decided it was a better idea to clean the DataTable for nulls before it is used. That led to the CleanDataTable method below, that replaces null values with zeros for a few integer type columns.

/// <summary>

/// In the case of null values in a data table, this method

/// will turn all nulls into zeros instead.

/// </summary>

public static DataTable CleanDataTable(DataTable dt)

{

  for (int a = 0; a < dt.Rows.Count; a++)

  {

    for (int i = 0; i < dt.Columns.Count; i++)

    {

      if (dt.Rows[a][i] == DBNull.Value)

      {

        Type type = dt.Columns[i].DataType;

        if (type == typeof(int) || type == typeof(float) || type == typeof(double))

        {

          dt.Columns[i].ReadOnly = false;

          dt.Rows[a][i] = 0.0F;

        }

      }

    }

  }

 

  return dt;

}

The point is that you only have to clean it once to avoid any workaround for handling null values.

* $4.95/month BlogEngine.net Hosting – Click Here!

Comments (4) -

 MH
MH
12/21/2006 9:24:37 PM #

I do it with a dataview .. the syntax is strange (to me), so I keep it handy

dv.RowFilter = "IsNull(COLUMN_NAME,'null') <> 'null'";

mhinze.com/.../

Mads Kristensen
Mads Kristensen
12/22/2006 5:41:45 AM #

MH, that also does the trick if you are able to work with a DataView and that is not always the case.

dave thieben
dave thieben
12/22/2006 11:35:18 AM #

Aren't you concerned that if the DataTable has to be persisted back to the db, that you have changed the null values?  Perhaps null has a different meaning than zero?

Mads Kristensen
Mads Kristensen
12/22/2006 11:43:36 AM #

Sure, then you probably don't want to use this method.

Pingbacks and trackbacks (1)+

Comments are closed

About the author

Mads Kristensen

Mads Kristensen
Program Manager at the Microsoft Web Platform team and founder of BlogEngine.NET.

More...

Month List

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer’s view in any way.