Checking a DataTable for Data

Whenever you retrieve a DataTable from a data source, there no guarantee that there is actual data in it. Before you start looking for rows, you should always validate that that is it’s not null and also there are rows. Here is a easy way to do it using extensions.

public static class DataTableExtensions
    /// <summary>
    /// Determines whether the specified <see cref="DataTable"/> has rows.
    /// </summary>
    /// <param name="dt">The table.</param>
    /// <returns>
    ///     <c>true</c> if the specified table has rows; otherwise, <c>false</c>.
    /// </returns>
    public static bool HasRows(this DataTable dt)
      return ((dt != null) && (dt.Rows != null) && (dt.Rows.Count > 0));

To use, write the following:

   var services = LoadServices();

   if (services.HasRows())
     //Do Work

Tip Submitted By: David McCarter