Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a column exists in a datatable

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?

like image 943
Rémi Avatar asked Jul 17 '13 17:07

Rémi


People also ask

How do you check if a column already exists in Datatable?

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

How do you check if a column exists in a table in SQL?

Colum view to check the existence of column Name in table SampleTable. IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA. COLUMNS WHERE table_name = 'SampleTable' AND column_name = 'Name' ) SELECT 'Column exists in table' AS [Status] ; ELSE SELECT 'Column does not exist in table' AS [Status];

How do I check if a DataRow column exists?

You can use the DataColumnCollection of Your datatable to check if the column is in the collection.


1 Answers

You can use operator Contains,

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

MSDN - DataColumnCollection.Contains()

like image 188
Aghilas Yakoub Avatar answered Oct 11 '22 11:10

Aghilas Yakoub