0

I'm trying to check to see if a DataTable object is null or not, but whenever the DataTable is null, my program keeps giving me an OleDBException.

I have this method to set up the DataTable

public DataTable setUpDataTable(String sql)
    {
        String connString = connDel;

        using (OleDbConnection conn = new OleDbConnection(connString))
        {
            OleDbCommand cmd = new OleDbCommand(sql, conn);

            try
            {
                conn.Open();
            }
            catch (NullReferenceException ex)
            {
                MessageBox.Show(ex.Message);
            }
            DataTable delTable = new DataTable();
            OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
            adapter.Fill(delTable);
            return delTable;

        }
    }

And here is where I call the method to initialize the DataTable object(the original method is in another class). I want to see if this DataTable is null.

DataTable duplicates = main.setUpDataTable(sql);

if (duplicates != null)
            return false;

The program doesn't get to the if statement at all, but throws an exception right at the initialization of the DataTable object. The method works when there is something in the DataTable, but throws the exception when it is null. How can I fix this?

ecco_
  • 3
  • 1
  • 3

1 Answers1

0

Try this..

You will get an empty DataTable if no records match, so you can check on the number of records returned:

if (duplicates != null && duplicates .Rows.Count > 0)
    return false;

Also please verify SQL select query.

Nalaka
  • 1,165
  • 7
  • 12
  • It still crashes when it fills the DataTable in setUpDataTable. Here is what I have for the SQL statement if it helps (Room Number is a String): SELECT DATE, BUILDING, [ROOM NUMBER], EQUIPMENT, [START TIME], [END TIME] FROM [DELIVERY DATA BASE]" + "WHERE DATE=#" + date.ToString("MM/dd/yyyy") + "# AND BUILDING='" + building + "' AND [ROOM NUMBER]='" + room + "' AND EQUIPMENT='" + equip + "' AND [START_TIME]=#" + start.ToString("MM/dd/yyyy") +"# AND [END TIME]=#" + end.ToString("MM/dd/yyyy") +"#" – ecco_ Mar 19 '15 at 17:03