简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM