Rashmi S
Rashmi S

Reputation: 267

Get datatype of column in datatable

I am trying to get dataType of datatable, code is

 for (int j = 0; j < dt.Columns.Count; j++)
 {
       columntypes[j] = dt.Columns[j].GetType().Name;//dt.Rows[0][j].GetType().Name;
 } 

checked dt.Rows[0][j].GetType().Name; works fine.But In case of empty datatable it throws a error,So i tried with dt.Columns[j].GetType().Name; but it doesnt give proper solution

Upvotes: 1

Views: 7446

Answers (3)

Rahul Tripathi
Rahul Tripathi

Reputation: 172378

You can try like this:

if(dt!=null && dt.Rows.Count > 0)
{
    for (int j = 0; j < dt.Columns.Count; j++)
     {
           columntypes[j] = dt.Columns[j].DataType.Name.ToString();
     } 
}

ie, you need to use the DataType property

Upvotes: 2

sujith karivelil
sujith karivelil

Reputation: 29006

You can use like this also:

 int j=0;
 foreach (DataColumn dc in DT.Columns)
    {
       columntypes[j++] = dc.DataType.Name.ToString();  
    }

Upvotes: 0

Rajan
Rajan

Reputation: 2425

The DataTable.Columns property is a DataColumnCollection, which can be indexed by column name to get a DataColumn, which has a DataType property. or You may do :

SqlCommand cmd = connection.CreateCommand(); 
cmd.CommandText = "SET FMTONLY ON; select column from table; SET FMTONLY OFF"; 
SqlDataReader reader = cmd.ExecuteReader();
SqlDbType type = (SqlDbType)(int)reader.GetSchemaTable().Rows[0] ["ProviderType"];

Upvotes: 1

Related Questions