LLaP
LLaP

Reputation: 2727

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

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

Upvotes: 1

Views: 162

Answers (1)

vcsjones
vcsjones

Reputation: 141678

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.

Upvotes: 4

Related Questions