How to check if a column exists in a datatable
You can use operator Contains
,
private void ContainColumn(string columnName, DataTable table)
{
DataColumnCollection columns = table.Columns;
if (columns.Contains(columnName))
{
....
}
}
MSDN - DataColumnCollection.Contains()
myDataTable.Columns.Contains("col_name")
For Multiple columns you can use code similar to one given below.I was just going through this and found answer to check multiple columns in Datatable.
private bool IsAllColumnExist(DataTable tableNameToCheck, List<string> columnsNames)
{
bool iscolumnExist = true;
try
{
if (null != tableNameToCheck && tableNameToCheck.Columns != null)
{
foreach (string columnName in columnsNames)
{
if (!tableNameToCheck.Columns.Contains(columnName))
{
iscolumnExist = false;
break;
}
}
}
else
{
iscolumnExist = false;
}
}
catch (Exception ex)
{
}
return iscolumnExist;
}
It is much more accurate to use IndexOf:
If dt.Columns.IndexOf("ColumnName") = -1 Then
'Column not exist
End If
If the Contains is used it would not differentiate between ColumName and ColumnName2.