Get a DataTable Columns DataType
Asked Answered
S

5

52
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()
Squiggle answered 12/3, 2012 at 2:20 Comment(0)
M
99

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

Medicine answered 12/3, 2012 at 2:24 Comment(1)
And any other type name, eg System.Collections.Specialized.StringDictionaryMultistage
Z
15

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

using System.Data;

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

or using column name :

if (dt.Columns["yourColumnName"].DataType == typeof(DateTime))
{
    //...
}
Zusman answered 28/4, 2019 at 15:22 Comment(0)
T
10
dt.Columns[0].DataType.Name.ToString()
Twain answered 8/10, 2014 at 6:22 Comment(1)
Please add more details about your answer e.g. explain why your code works etc.Cas
B
0

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.

Bustos answered 28/3, 2017 at 11:34 Comment(0)
K
-2
if (dr[dc.ColumnName].GetType().ToString() == "System.DateTime")
Kosel answered 16/3, 2020 at 6:27 Comment(1)
Getting the type, then converting to a string to compare to seems a little redundant.Whydah

© 2022 - 2024 — McMap. All rights reserved.