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?
You can use operator Contains , private void ContainColumn(string columnName, DataTable table) { DataColumnCollection columns = table. Columns; if (columns. Contains(columnName)) { .... } }
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];
You can use the DataColumnCollection of Your datatable to check if the column is in the collection.
You can use operator Contains
,
private void ContainColumn(string columnName, DataTable table) { DataColumnCollection columns = table.Columns; if (columns.Contains(columnName)) { .... } }
MSDN - DataColumnCollection.Contains()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With