DevGuy
DevGuy

Reputation: 167

Determine if DataColumn is date only

I have a DataTable object and can access its Columns collection. For each item of this collection I need to determine the type of the column and return it as one of the following string: 'string' 'number' 'boolean' 'date' 'datetime' 'timeofday'.

So I do something like the following:

foreach (DataColumn column in table.Columns) {
  string colType = DermineColumnType(column);
}

. . . . 

string DeterminColumnType(DataColumn column) {
  Type sysType = column.DataType
  if (sysType == typeof(Boolen)
      return "boolean";
  else if (sysType == typeof(Decimal) || sysType == typeof(Double) || sysType == typeof(Int32) ...)
      return "number";
  . . . . . . 
  else
      return "string";

}

The problem is with 'date', 'datetime' and 'timeofday' values - I can't find any information in DataColumn class which allows me to determine whether this column is defined in database table as just "date", "time" or "datetime". DataType property of DataColumn class always returns System.DateTime type for all these cases. Is there any way to get this information based only on DataColumn and/or DataTable objects, without executing additional SQL statements?

Upvotes: 2

Views: 3647

Answers (2)

Ajay Baraiya
Ajay Baraiya

Reputation: 9

You can directly get the type of data column by following code

 foreach (DataColumn column in table.Columns) {
  var v = column.GetType()
Return v.ToString()
}

Upvotes: 0

Niko Carrizo
Niko Carrizo

Reputation: 86

Date and Time are not valid data types for a DataColumn. DateTime and TimeSpan are the only date/time related data types.

It seems you won't be able to tell just from the type whether it's a Date or Time, you will need to look at the data inside the DateTime object or from the database.

For more information: http://msdn.microsoft.com/en-us/library/system.data.datacolumn.datatype.aspx

Upvotes: 0

Related Questions