mHelpMe
mHelpMe

Reputation: 6668

dynamically specifying DataTable columns

I have a object[,] myObj. I also have string[] fieldTypes. I want to get the data from my object array into a DataTable.

I want the DataTable columns though to be of the correct type, i.e. string, datetime, double etc. This is where the fieldTypes array comes in.

So let me start with a basic example:

myObj has n rows and 3 columns. fieldTypes will be an array of length 3 (i.e. the same number of columns as myObj)

Let's say my

 fieldTypes = {'string', 'DateTime', 'double' }

Is there a way to setup up my DataTable to have correct columns using the fieldTypes?

Something like below (I know what I have written below is incorrect)

DateTable dt = new DataTable();
for(int i=0; i < fieldTypes.Length; i++)
{
   dt.Columns.Add(myColName, typeof(fieldTypes[i]));
}

I would then need to cast the values in myObj so they could be added to my DataTable. Is this possible?

Upvotes: 0

Views: 903

Answers (1)

andrei.ciprian
andrei.ciprian

Reputation: 3025

You need to have column names and types specified. Considering you already mapped type names to types.

I'd use a column specification class like:

class ColSpec
{
    public Type Type { get; set; }
    public string Name { get; set; }
}

and a jagged array instead of a multidimensional one, lets you add rows easier, no cast required.

var colspecs = new ColSpec[] { 
    new ColSpec { Type = typeof(int), Name = "int" }, 
    new ColSpec { Type = typeof(string), Name = "string" } };
var dt = new DataTable();
dt.Columns.AddRange (colspecs.Select(x=> new DataColumn(x.Name, x.Type) ).ToArray()) ;
// single row jagged array 
object[][] myObj = new object[1][];
// 2 colums per row
myObj[0] = new object[2] {100, "string"};
foreach (object[] objs in myObj)
    dt.Rows.Add(objs);

Upvotes: 1

Related Questions