views:

2618

answers:

3

How do I check for the existence of a column in a datarow? I'm building datatables to organize some data that I've already pulled back from the db. Depending on the type of data in each row I need to create a datatable with different columns. Then later on I want to check and see if the datatable i am looking at has a certain column. I know I can catch the exception and handle it that way, but I'm curious if there is a property or method on the datarow object that will do this for me?

Here's how I can do it by catching the exception:

public static String CheckEmptyDataRowItem(DataRow row, String rowName, String nullValue)
{
    try
    {
        return row[rowName].ToString();
    }
    catch (System.ArgumentException)
    {
        return nullValue;
    }
}
+1  A: 

DataTables have that schema info, so check if the Row's Table's Columns collection contains the field.

Wyatt Barnett
+1  A: 

There is no property supplied by the framework that will do this. You can however accomplish this without adding a try/catch that will regularly catch into the logical execution.

Use a DataTableReader object to read the table hosting the row. You can generate the reader from the properties in the row itself. The reader object provides the required functions to verify if a column exists.

Try something along the lines of:

public static bool DoesColumnExistInRow(DataRow row, string columnName)
{
   bool output = false;

   DataTableReader reader = null;
   try 
   {
      reader = row.Table.CreateDataReader();
      if (reader.HasRows) 
      {
          reader.Read();
          for (int i = 0; i < reader.FieldCount; i++) 
          {
             if (reader.GetName(i).Equals(columnName)) 
             {
                 output = true;
                 break;
             }       
      }
   }
   catch (Exception ex)
   { 
      // handle any unexpected errors creating the reader
   }
   finally
   {
      if (reader != null) 
      {
         reader.Dispose();
      }
   }

   return output;
}
Mark
Do you consider the the DataTableReader approach a better practice than the try catch I have above?
Tone
It entirely depends on the amount you'll be using the function.Typically you should avoid using try/catch in the normal flow. There's significantly more overhead in try/catch than testing through other methods.In my example, the try/catch/finally block is there to catch unexpected errors (which is best practice). Obviously there's significantly more code in my approach but I would guess (I haven't benched it) that it's actually faster if you're running this check often.If you just have to check once or twice, use your approach.If you're doing it all the time, DataTableReader
Mark
ok that makes sense. I like your approach. Thanks for the explanation.
Tone
+14  A: 

You can simply check like this:

return (row.Table.Columns.Contains(columnName)) ? true : false;
Gaurav
nice solution, helped me
Amr ElGarhy

related questions