ADO.NET DataRow - check for column existence

Datatableado.netDatarow

Datatable Problem Overview


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 database. 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;
    }
}

Datatable Solutions


Solution 1 - Datatable

You can simply check like this:

return row.Table.Columns.Contains(columnName);

Solution 2 - Datatable

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionToneView Question on Stackoverflow
Solution 1 - DatatableGaurav View Answer on Stackoverflow
Solution 2 - DatatableWyatt BarnettView Answer on Stackoverflow