Is it possible to define a column type in DataTable at run time?

160 Views Asked by At

I would like to create a DataTable but I don't know the types of columns at compile time. Therefore, I would like the columns types to be decided at run-time.

WHAT I'VE TRIED:

First, I get some data from Excel:

Type tempCheck = (dynamic)(xlRange.Cells[1, currentColumnsCount] as Excel.Range).Value2.GetType();

Then I try to use the type to create a column.

myDataTable.Columns.Add(columnName, typeof(tempCheck.GetType());

I get the error:

The type or namespace name 'tempCheck' could not be found (are you missing a using directive or an assembly reference?)

1

There are 1 best solutions below

1
On BEST ANSWER

tempCheck is already a type, so you don't need the typeof:

myDataTable.Columns.Add(columnName, tempCheck);

typeof is an operator that is used to get an instance of System.Type from a type name, and this is done at compile time.

The error "The type or namespace name 'tempCheck' could not be found" is coming because since typeof is looking for a compile-time type, it's literally looking for a type called tempCheck, like a class or delegate, etc.