C# – How to check if a column exists in a datatable

argumentexceptioncdatatable

I have a datable generated with the content of a csv file. I use other information to map some column of the csv (now in the datatable) to information the user is required to fill.

In the best world the mapping would be alway possible. But this is not reality… So before I try to map the datatable column value I would need to check if that column even exist. If I don't do this check I have an ArgumentException.

Of course I can check this with some code like this :

try
{
    //try to map here.
}
catch (ArgumentException)
{ }

but I have for now 3 columns to map and some or all might be existing/missing

Is there a good way to check if a column exist in a datatable?

Best Answer

You can use operator Contains,

private void ContainColumn(string columnName, DataTable table)
{
    DataColumnCollection columns = table.Columns;        
    if (columns.Contains(columnName))
    {
       ....
    }
}

MSDN - DataColumnCollection.Contains()