How to check if a column exists in a data table

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

In a better world, mapping will always be possible. But this is not a reality ... Therefore, before trying to match the value of a data column, I will need to check if this column exists. If I do not do this check, I have an ArgumentException.

Of course, I can verify this with some code:

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

but now I have 3 columns to map and some or all may or may not exist

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

+80
c # datatable argumentexception
Jul 17 '13 at 17:26
source share
5 answers

You can use operator Contains ,

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

MSDN - DataColumnCollection.Contains ()

+171
Jul 17 '13 at 17:36
source share
— -
 myDataTable.Columns.Contains("col_name") 
+67
Feb 05 '14 at 14:14
source share

For multiple columns, you can use code similar to the one below. I just went through this and found an answer to check for 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; } 
+8
Mar 12 '15 at 5:04
source share

You can see the Columns property of this DataTable , this is a list of all columns in the table.

 private void PrintValues(DataTable table) { foreach(DataRow row in table.Rows) { foreach(DataColumn column in table.Columns) { Console.WriteLine(row[column]); } } } 

http://msdn.microsoft.com/en-us/library/system.data.datatable.columns.aspx

0
Jul 17 '13 at 17:37
source share
 DataColumnCollection col = datatable.Columns; if (!columns.Contains("ColumnName1")) { //Column1 Not Exists } if (columns.Contains("ColumnName2")) { //Column2 Exists } 
0
Jul 24. '19 at 12:19
source share



All Articles