Jeremy Thompson
Jeremy Thompson

Reputation: 65534

Get a DataTable Columns DataType

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()

Upvotes: 52

Views: 159320

Answers (5)

VDWWD
VDWWD

Reputation: 35514

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))
{
    //...
}

Upvotes: 15

Vinod Parmar
Vinod Parmar

Reputation: 17

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

Upvotes: -2

Arpit Trivedi
Arpit Trivedi

Reputation: 161

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.

Upvotes: 0

Natarajan Sambantham
Natarajan Sambantham

Reputation: 143

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

Upvotes: 10

user596075
user596075

Reputation:

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

Upvotes: 99

Related Questions