Get a DataTable Columns DataType

C#.NetDatatableDatagridviewcolumn

C# Problem Overview


DataTable dt = new DataTable();  
dt.Columns.Add(new DataColumn(gridColumn1, typeof(bool)));

I was expecting the result of the below line to include info about the DataColumns Type (bool):

?dt.Columns[0].GetType()

C# Solutions


Solution 1 - C#

What you want to use is this property:

dt.Columns[0].DataType

The DataType property will set to one of the following:

Boolean
Byte
Char
DateTime
Decimal
Double
Int16
Int32
Int64
SByte
Single
String
TimeSpan
UInt16
UInt32
UInt64

DataColumn.DataType Property MSDN Reference

Solution 2 - C#

You could always use typeof in the if statement. It is better than working with string values like the answer of Natarajan.

if (dt.Columns[0].DataType == typeof(DateTime))
{
}

Solution 3 - C#

dt.Columns[0].DataType.Name.ToString()

Solution 4 - C#

You can get column type of DataTable with DataType attribute of datatable column like below:

var type = dt.Columns[0].DataType

dt: DataTable object.

0: DataTable column index.

Solution 5 - C#

if (dr[dc.ColumnName].GetType().ToString() == "System.DateTime")

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJeremy ThompsonView Question on Stackoverflow
Solution 1 - C#user596075View Answer on Stackoverflow
Solution 2 - C#VDWWDView Answer on Stackoverflow
Solution 3 - C#Natarajan SambanthamView Answer on Stackoverflow
Solution 4 - C#Arpit TrivediView Answer on Stackoverflow
Solution 5 - C#Vinod ParmarView Answer on Stackoverflow