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

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s