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?
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;
}
You can look at the Columns
property of a given DataTable
, it 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
DataColumnCollection col = datatable.Columns;
if (!columns.Contains("ColumnName1"))
{
//Column1 Not Exists
}
if (columns.Contains("ColumnName2"))
{
//Column2 Exists
}
참고URL : https://stackoverflow.com/questions/17706326/how-to-check-if-a-column-exists-in-a-datatable
'Development Tip' 카테고리의 다른 글
Windows에서 GPG 파일을 해독하기 위해 개인 / 비밀 ASC 키를 내보내는 방법 (0) | 2020.09.25 |
---|---|
ZSH iterm2 increase number of lines history (0) | 2020.09.25 |
How to get the current url name using Django? (0) | 2020.09.25 |
can't get correct value of keyboard height in iOS8 (0) | 2020.09.25 |
Meaning of top, ascent, baseline, descent, bottom, and leading in Android's FontMetrics (0) | 2020.09.25 |